代码如下
[code="java"]public class Main {
int x = 0;
public class Runner implements Runnable
{
public void run()
{
int current = 0;
for(int i=0;i<4;i++)
{
current=x;
System.out.println("The thread is "+Thread.currentThread().getName()+"
and current is "+current+",");
x=current+2;
}
}
}
public void go()
{
Runner r1 = new Runner();
[color=red]new Thread(r1,"thread1").start();
new Thread(r1,"thread2").start();[/color]
}
public static void main(String[] args)
{
new Main().go();
}
}
[/code]
这个程序很简单,首先定义了一个实例变量X,初始值为0,然后实例化了一个runner,通过new Thread定义了两个线程(thread1和thread2),将runner的实例r1作为这两个线程的target,注意,这里两个线程用的是同一个target,所以这两个线程共享了实例变量x,按说这两个线程应该是对该变量进行加一操作,但是在我的电脑上,跑出来结果如下
init:
deps-jar:
compile-single:
run-single:
The thread is thread1 and current is 0,
The thread is thread1 and current is 2,
The thread is thread1 and current is 4,
The thread is thread1 and current is 6,
The thread is thread2 and current is 0,
The thread is thread2 and current is 2,
The thread is thread2 and current is 4,
The thread is thread2 and current is 6,
成功生成(总时间:0 秒)
请注意,这像是两个线程各自拥有一个x的复本,然后分别对自己拥有的x进行了循环+1的操作,而不是两个线程对同一个x进行+1操作。
按照教科书上的说法,因为两个线程共享同一个target,所以这两个线程应该共享同一个变量x,所以我想问问牛人,这是不是双核的原因?谢谢了