[英]Threads and Multithreading in Java
如果一個服務線程已經在該塊中等待notify
調用,則另一個服務線程如何才能進入同步塊?
我已經用其他示例進行了測試,當其中一個線程處於同步塊中並且新線程在舊線程離開該塊后立即進入同步塊時,所有其他線程似乎都等待進入同步塊:
class ThreadClassNotifier implements Runnable {
private Message msg;
public ThreadClassNotifier(Message msg) {
this.msg = msg;
}
@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name+" started");
try {
Thread.sleep(1000);
synchronized (msg) {
msg.setMsg(name+" Notifier work done");
msg.notify();
// msg.notifyAll();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class ThreadClassWaiter implements Runnable {
private Message msg;
public ThreadClassWaiter(Message m){
this.msg=m;
}
@Override
public void run() {
String name = Thread.currentThread().getName();
synchronized (msg) {
try{
System.out.println(name+" waiting to get notified at time:"+System.currentTimeMillis());
Thread.sleep(10000);
msg.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(name+" waiter thread got notified at time:"+System.currentTimeMillis());
//process the message now
System.out.println(name+" processed: "+msg.getMsg());
}
}
}
public class ThreadMain {
public static void main(String[] args) throws InterruptedException {
Message msg = new Message("process it");
ThreadClassWaiter waiter = new ThreadClassWaiter(msg);
new Thread(waiter,"waiter").start();
ThreadClassWaiter waiter1 = new ThreadClassWaiter(msg);
new Thread(waiter1, "waiter1").start();
System.out.println("All the threads are started");
}
}
“如果另一個服務線程已經在該塊中等待通知調用,另一個服務線程如何進入同步塊?”
從Java文檔獲取Object.wait()
當前線程必須擁有該對象的監視器。 該線程釋放此監視器的所有權,並等待直到另一個線程通過調用notify方法或notifyAll方法通知等待在該對象監視器上等待的線程喚醒。 然后線程等待,直到它可以重新獲得監視器的所有權並恢復執行 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.