【发布时间】:2021-09-10 06:55:02
【问题描述】:
我遇到了以下 e 示例,用于从某个网站实现自定义挂起和等待。
// Suspending and resuming a thread the modern way.
class NewThread implements Runnable {
String name; // name of thread
Thread t;
boolean suspendFlag;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
suspendFlag = false;
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for (int i = 15; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(200);
synchronized(this) {
while (suspendFlag) {
wait();
}
}
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
void mysuspend() {
suspendFlag = true;
}
synchronized void myresume() {
suspendFlag = false;
notify();
}
}
class SuspendResume {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
try {
Thread.sleep(1000);
ob1.mysuspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.myresume();
...................
我更关心 ob1.mysuspend() 和 ob1.myresume() 调用。当我的挂起被调用时,ob1 将被放入与其正在使用的可运行对象关联的阻塞队列中。当 ob1 调用 myresume 时,它是如何工作的,因为 ob1 已经在等待同一对象的队列中,等待的对象是否可以进入另一个同步方法,然后向自身发出通知?这是如何工作的?我错过了什么?
【问题讨论】:
-
线程进入
wait()时释放锁,其他线程可以获取。 -
Re, "当 ob1 调用 myresume,..." 在你的程序中调用
myresume()的唯一线程是 main 线程。不确定“ob1 调用...”是什么意思,但程序中的ob1.myresume()语句由主线程执行(即,由调用main(...)例程的同一个 Java 线程执行。)该调用清除了suspendFlag属于ob1对象,它notify()s 是ob1对象。
标签: java multithreading synchronization thread-safety