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

线程交替问题
想定义两个线程交替运行,以sum为指标,sum=0 运行线程0,在线程0里把,sum设为1;sum=1时运行线程1,在线程1里,把sum置为0,依次循环,并计算线程交替时间。
结果应该是
0
1
0
1
0
1
0
1
。。。。

高手看看我的程序哪里出错:

class Number0 extends Thread{
   
  //public long lasting;
  public void run()
  {
  if (SumStore.sum == 0)
  {
  SumStore.sum = 1;
  System.out.println("thread0 and sum is " + SumStore.sum);
   
  }
  //lasting = System.currentTimeMillis();
  //long cost =
  //System.out.println("threadswitch time " + cost);
  //return;
  //}
  }
   
   
}


class Number1 extends Thread{
   
  public long starting,lasting;
  public void run()
  {
   
  if (SumStore.sum == 1)
  {
  SumStore.sum = 0;  
  System.out.println("thread1 and sum is " + SumStore.sum);
  }
   
   
   
  //starting = System.currentTimeMillis();
  //long cost = starting - lasting;
  //System.out.println("threadswitch time " + cost);
  }
}

class SumStore {

  public static int sum = 0;

}
/////////////////////////////////////////////////////////////////////////
public class threadswitching
{

/**
  * @param args
  */
public static void main(String[] args) throws Exception
{
   
  for(int i=1; i<3; i++){
Thread t1 = new Number0();
Thread t2 = new Number1();
t1.start();
t2.start();
  }

}
}
 

------解决方案--------------------
Java code
 
class Number0 extends Thread {
// public long lasting;
public void run() {
while (true) {
synchronized (SumStore.class) {
try {
if (SumStore.sum == 0) {
SumStore.sum = 1;
System.out.println("thread0 and sum is  "
+ SumStore.sum);
}
SumStore.class.notifyAll();
Thread.sleep(300);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// lasting = System.currentTimeMillis();
// long cost =
// System.out.println("threadswitch time " + cost);
// return;
// }
}

}

class Number1 extends Thread {
public long starting, lasting;
public void run() {
while (true) {
synchronized (SumStore.class) {
try {
SumStore.class.wait();
if (SumStore.sum == 1) {
SumStore.sum = 0;
System.out.println("thread1 and sum is  "
+ SumStore.sum);
}
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// starting = System.currentTimeMillis();
// long cost = starting - lasting;
// System.out.println("threadswitch time " + cost);
}
}

class SumStore {