日期:2014-05-20 浏览次数:20888 次
package thread1;
// this program is puzzle when run on 2 core ,I do not know why ,it just
// do not stop
class ThreadA {
  public static void main(String[] args) {
    ThreadB b = new ThreadB();
    b.start();
    System.out.println("b is start....");
    synchronized (b)// 括号里的b是什么意思,起什么作用?
    {
      try {
        System.out.println("Waiting for b to complete...");
        b.wait();// 这一句是什么意思,究竟让谁wait?
        System.out.println("Completed.Now back to main thread");
      } catch (InterruptedException e) {
        System.out.println("InterruptedException");
      }
    }
    System.out.println("main:Total is :" + b.total);
  }
}
class ThreadB extends Thread {
  int total;
  public void run() {
    synchronized (this) {
      System.out.println("ThreadB is running..");
      for (int i = 0; i < 10; i++) {
        total += i;
        System.out.println("total is " + total);
      }
      notify();
      /*
       * try { System.out.println("b is waiting" ); wait();
       *  } catch (InterruptedException e) { System.out.println("InterruptedException"); }
       */
    }
    System.out.println("AFTER notify");
    System.exit(0);
  }
}
public class ThreadTest
{
    public static void main(String[] args)
    {
        ThreadB b = new ThreadB();
        b.start();
        System.out.println("b is start....");
        try
        {
            Thread.sleep(2000);//没有这个的话,单CPU上运行,成功的可能性很大
        }
        catch (InterruptedException ex)
        {
            ex.printStackTrace();
        }
        synchronized (b)// 括号里的b是什么意思,起什么作用?
        {
            try
            {
                Thread.sleep(2000);
                System.out.println("Waiting for b to complete...");
                b.wait();// 这一句是什么意思,究竟让谁wait?
                System.out.println("Completed.Now back to main thread");
            }
            catch (InterruptedException e)
            {
                System.out.println("InterruptedException");
            }
        }
        System.out.println("main:Total is :" + b.total);
    }
}
class ThreadB extends Thread
{
    int total;
    public void run()
    {
        synchronized (this)
        {
            System.out.println("ThreadB is running..");
            for (int i = 0; i < 100; i++)
            {
                total += i;
                System.out.println("total is " + total);
            }
            notify();
            /*
             * try { System.out.println("b is waiting" ); wait();
             *  } catch (InterruptedException e) {
             * System.out.println("InterruptedException"); }
             */
        }
        System.out.println("AFTER notify");
    }
}