我试图写一个简单的例子来演示远程控制器的操作。通过控制台接受输入,并相应地打印一条消息。
两个线程都运行无限循环:主线程等待通知,而另一个线程等待控制台输入。
我想知道如何解决这个问题。问题是通知并没有停止等待:换句话说,"等待之前"的字样是打印出来的,但"等待之后"的字样不是。顺便说一句,没有while(true)循环,它工作得很好(只需按下一个按钮)。
非常感谢
public class MainTV {
public static int lastRemoteCode = 0;
public static void main(String[] args){
RemoteControllerThread remote = new RemoteControllerThread();
remote.start();
synchronized(remote){
while(true){
try {
System.out.println("before wait");
remote.wait();
System.out.println("after wait");
switch (lastRemoteCode){ //we use switch because there are many code options
case 0:
System.out.println("Error with remote button reading");
break;
case 3:
System.out.println("Volume Down button was pressed now!");
break;
case 4:
System.out.println("Volume Up button was pressed now!");
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
第二类(模拟遥控器):
import java.util.Scanner;
public class RemoteControllerThread extends Thread{
public void run(){
synchronized(this){
Scanner in = new Scanner(System.in);
while(true){
System.out.println("Press a button in the remote please...");
int code = in.nextInt();
MainTV.lastRemoteCode = code;
System.out.println("before notify");
notify();
System.out.println("after notify");
}
}
}
}
两个线程在同一对象上同步,this
与remote
指代同一对象,由于这两个同步块内部都有无限循环,这就产生了问题。其中一个线程将等待另一个线程完成,但这永远不会发生(因为存在无限循环)。
要解决此问题,应该只同步需要同步的代码,如wait()
和notify()
调用。
我认为您的代码有两个问题。
-
当主线程执行达到
synchronized(remote)
时,它可能不会继续,因为远程控制器线程(可能)已经锁定了remote
对象。将remote.start()
移动到synchronized(remote)
块中。 -
为了让执行从
wait
继续,您需要在notify
之后释放对象锁。更改线程中的同步块:
-
public void run() {
Scanner in = new Scanner(System.in);
while(true){
System.out.println("Press a button in the remote please...");
int code = in.nextInt();
MainTV.lastRemoteCode = code;
System.out.println("before notify");
synchronized(this) {
notify();
}
System.out.println("after notify");
}
}
引用notify()
JavaDoc:
在当前线程放弃对该对象的锁定之前,唤醒的线程将无法继续
你的遥控器永远不会松开锁。如果你用while
切换synchronized
,你的机会很小,但通常你的遥控器会立即取回锁。例如,以下工作:
class RemoteControllerThread extends Thread {
public void run() {
while (true) {
synchronized (this) {
Scanner in = new Scanner(System.in);
System.out.println("Press a button in the remote please...");
int code = in.nextInt();
MainTV.lastRemoteCode = code;
System.out.println("before notify");
notify();
System.out.println("after notify");
}
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}