【发布时间】:2015-12-15 15:16:01
【问题描述】:
考虑这个简单的多线程示例:
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(); ?
【问题讨论】:
-
请查一下run()和start()的区别
-
Thread成为Runnable一定是 Java API 中最愚蠢的事情之一。 -
@MarkoTopolnik:我的线程没有实现 Runnable 。
-
我建议你再检查一次:) 这是不可能的。顺便说一句,这不是你的错,而是 JDK 的错。
-
package java.lang; public class Thread implements Runnable { ... }.
标签: java multithreading mutex thread-synchronization