线程wait()会影响主线程吗?

时间:2015-09-18 12:54:12

标签: java multithreading mutex thread-synchronization

考虑多线程示例的这个简单尝试:

public class LetsMutexThreads {

    public static Object MUTEX = new Object();

    private static class Thread1 extends Thread {
        public void run() {
            synchronized (MUTEX) 
            {
                System.out.println("I'm thread 1 , goint to take a nap...");
                try 
                {
                    MUTEX.wait();
                } 

                catch (InterruptedException e) 
                {
                    e.printStackTrace();
                }

                System.out.println("T1 : That's it , I'm done ...");
            }
        }
    }

    private static class Thread2 extends Thread {
        public void run() {
            synchronized (MUTEX) 
            {
                System.out.println("Thread 2 : Let's rock N roll !");
                System.out.println("Waking up my buddy T1 ...");
                MUTEX.notify();
            }
        }
    }

    public static void main(String[] args) 
    {
        Thread2 t2 = new Thread2();
        Thread1 t1 = new Thread1();
        t1.run();
        t2.run();
    }

}

我试图允许Thread1在等待时进入睡眠状态,然后让Thread2 使用notify()唤醒Thread1,但他没有机会。

为什么Thread1的wait()会影响主线程执行t2.run();

2 个答案:

答案 0 :(得分:4)

您不能尝试使用run()方法启动线程。它实际上并不创建新线程,它在当前线程中运行代码。使用thread.start()代替,以便在单独的(新)线程中执行代码

答案 1 :(得分:3)

这是错误的:

Thread2 t2 = new Thread2();
Thread1 t1 = new Thread1();
t1.run();
t2.run();

将其更改为:

Thread2 t2 = new Thread2();
Thread1 t1 = new Thread1();
t1.start();
t2.start();