gpt4 book ai didi

java - 暂停恢复线程 : Java

转载 作者:行者123 更新时间:2023-11-30 06:16:15 25 4
gpt4 key购买 nike

当我运行这段代码时,它会显示以下输出:

一:15
二:15
一:14
二:14
二:13
一:13
二:12
一:12
一:11
二:11
线程 1 暂停
二:10
二:9
二:8
二:7
二:6
线程 1 已恢复
线程 2 挂起
线程 2 恢复

输出不会持续到最后一:1二:1NewThread1类的myresume方法没有执行?这背后的原因是什么?

NewThread1的代码如下:

class NewThread1 implements Runnable{
String name;
Thread t;
boolean suspendFlag;

NewThread1(String threadname){
name = threadname;
t = new Thread(this, name);
suspendFlag = false;
t.start();
}

@Override
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("New thread1 Interrupted");
}
}
synchronized void myresume(){
suspendFlag = false;
}
void mysuspend(){
suspendFlag = true;
}
}

NewThread1的代码如下:(这里定义了main()方法)

public class Suspend_ResumeThreads {
public static void main(String args[]){
NewThread1 ob1 = new NewThread1("One ");
NewThread1 ob2 = new NewThread1("Two ");

try{
Thread.sleep(1000);
ob1.mysuspend();
System.out.println("Thread 1 suspended");
Thread.sleep(1000);
ob1.myresume();
System.out.println("Thread 1 resumed");

ob2.mysuspend();
System.out.println("Thread 2 suspended");
Thread.sleep(1000);
ob2.myresume();
System.out.println("Thread 2 resumed");

}catch(InterruptedException e){
System.out.println("Main Interrupted");
}

try{
ob1.t.join();
ob2.t.join();
}catch(InterruptedException e){
System.out.println("Main interrupeted in join()");
}
System.out.println("Main exiting..");
}
}

最佳答案

使用notifyAll 中断wait(): put

this.notifyAll();

进入您的 myresume() 函数。但是请时刻准备好丢失此通知;特别是当当前没有线程在等待时,它仍然会成功。

确保在相同对象上同步/等待/通知。一个常见的错误是在 this 上进行同步,但没有意识到在匿名内部类的上下文中,this 可能有所不同。更糟糕的是,重构代码时它可能会发生变化!最佳做法是在某个地方始终使用 Object lock = new Object(); synchronize(lock) ... lock.wait(); ... lock.notifyAll(); 以避免此类编程(和重构)错误。

除非你让suspendFlagvolatile,否则不同的线程也有可能看到这个字段的不同值(如果它不是volatile ,线程可能会在 CPU 缓存中保留一份本地副本)。因此,让 mysuspend 也同步也可能很好。

在某些情况下,您可能需要切换到更高级的同步,例如 java.util.concurrent.locks.Lockjava.util.concurrent.Semaphore .

关于java - 暂停恢复线程 : Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27617222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com