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

问一个关于线程同步的小白问题,大家指点一下。
Java code

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();
        }
    }
}



上面代码里ThreadB中run()的this就是b对象吧?
在b.start();之后一定会先执行主线程里 synchronized (b) {...这段?这是有保证的?

------解决方案--------------------
synchronized (b) {....}锁住当前线程,等待该线程执行完执行其他线程。
------解决方案--------------------
Java code

    /**
     * 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();

------解决方案--------------------
探讨

引用:

synchronized (b) {....}锁住当前线程,等待该线程执行完执行其他线程。

我想问synchronized (b) {....}一定会在run方法之前获得锁吗?

------解决方案--------------------
1 this 就是b.

2 "在b.start();之后一定会先执行主线程里 synchronized (b) {...这段?这是有保证的?" 
这是没有保证的。
但是主线程一直在执行,而线程b 需要经过线程调度,才能运行。所以虽无保证,但通常是主线程
“synchronized (b) {...这段”先执行。
如果想看看两个线程同时争抢的情况,可以在 b.start();之后,加一短暂(几毫秒)的sleep.