日期:2014-05-20 浏览次数:20631 次
public class ThreadA { public static void main(String[] args) { ThreadB b = new ThreadB(); b.start(); synchronized (b) { try { System.out.println("Waiting for b to complete..."); b.wait(); } catch (InterruptedException e) { } System.out.println("Total is: " + b.total); } } } class ThreadB extends Thread { int total; public void run() { synchronized (this) { System.out.println("ThreadB"); for (int i = 0; i < 100; i++) { total += i; } notify(); } } }
/** * Causes this thread to begin execution; the Java Virtual Machine * calls the <code>run</code> method of this thread. * <p> * The result is that two threads are running concurrently: the * current thread (which returns from the call to the * <code>start</code> method) and the other thread (which executes its * <code>run</code> method). * <p> * It is never legal to start a thread more than once. * In particular, a thread may not be restarted once it has completed * execution. * * @exception IllegalThreadStateException if the thread was already * started. * @see #run() * @see #stop() */ public synchronized void start() { /** * This method is not invoked for the main method thread or "system" * group threads created/set up by the VM. Any new functionality added * to this method in the future may have to also be added to the VM. * * A zero status value corresponds to state "NEW". */ if (threadStatus != 0 || this != me) throw new IllegalThreadStateException(); group.add(this); start0(); if (stopBeforeStart) { stop0(throwableFromStop); } } private native void start0();
------解决方案--------------------