我创建了下列程序,它使用相同的线程实例运行两个线程。我初始化了一个计数器,当每个线程运行时,计数器的值应该被执行,最后它应该在控制台中输出。线程运行时计数器的值没有被执行
public class MTThread {
static int count = 0;
public static void main(String arg[]){
System.out.println("Main started");
MTThreadInner in1= new MTThreadInner(1,count);
MTThreadInner in2= new MTThreadInner(2,count);
in1.start();
in2.start();
while (true) {
try {
in1.join();
in2.join();
break;
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Main finished, count = :"+ count);
}}
class MTThreadInner extends Thread {
int num; int counter;
MTThreadInner(int i,int z) {
counter=z;
num = i;
}
public void run(){
// TODO Auto-generated constructor stub
yield();
System.out.println("This ran Thread "+ num);
counter=counter+1;
}
}
但是输出总是显示计数为 “0”:
主要开始
此跑线程1
此跑线程2
主要成品,计数=: 0
它应该打印'count = 0'你能解释一下为什么你希望'count'完全改变吗? –
当thread1结束时,该值将增加1,并且在该线程运行两次后,值也会增加,但我认为计数值没有被返回 – Splasher
每个线程都将其自身的本地副本值0并将其递增为1.这不会与'count'共享或在任何地方复制。 –