日期:2014-05-20  浏览次数:20718 次

一个线程问题求解
public class Machine implements Runnable{
  private int a=0;
  public void run(){
    for(a=0;a<50;a++){
      System.out.println(Thread.currentThread().getName()+":"+a);
      try{
        Thread.sleep(100);
      }catch(InterruptedException e){throw new RuntimeException(e);}
    }
  }
  public static void main(String args[]){
    Machine machine=new Machine();
    Thread t1=new Thread(machine);
    Thread t2=new Thread(machine);
    t1.start();
    t2.start();
  }
} 这个打印结果为什么a=0有2次?

------解决方案--------------------
引用:
public class Machine implements Runnable{
  private int a=0;
  public void run(){
    for(a=0;a<50;a++){
      System.out.println(Thread.currentThread().getName()+":"+a);
      try{
……

楼主这段代码只是说明了线程的并发执行而已
至于为什么一开始输出的是两个0:
“一个线程打印了0,后睡眠,另一个线程依然从0开始打印,所以两次。”
这也是二楼说的,不过二楼后半部分说法感觉有点问题
因为你的代码根本就没有涉及到线程互斥
后续的输出无法预测,甚至有些a的值打印不出来
要互斥必须加锁

public class Machine implements Runnable{
  private int a=0;
  private Object object=new Object();
  public void run(){
  synchronized (object) {
  for(a=0;a<50;a++){
      System.out.println(Thread.currentThread().getName()+":"+a);
      try{
        Thread.sleep(100);
      }catch(InterruptedException e){throw new RuntimeException(e);}
    }
}
    
  }
  public static void main(String args[]){
    Machine machine=new Machine();
    Thread t1=new Thread(machine);
    Thread t2=new Thread(machine);
    t1.start();
    t2.start();
  }
}