gpt4 book ai didi

java - 并行执行线程超时

转载 作者:太空宇宙 更新时间:2023-11-04 12:55:19 25 4
gpt4 key购买 nike

处理并行线程时,输出应该是:“wait,done”!目前它是:“等等,不应该显示,完成”。有人可以帮忙吗?
我的主要:

public class Test {
public static void main(String[] args) {
Supervisor a = new Supervisor();
System.out.println("done");
}
}

类主任:

public class Supervisor {       
public Supervisor() {
Calculate t1 = new Calculate();
t1.start();
synchronized(t1){
System.out.println("wait");
try {
t1.wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

和计算器类:

public class Calculate extends Thread {
public Calculate(){}

@Override
public void run() {
synchronized(this){
try {
Thread.sleep(10000);
System.out.println("not supposed to be shown");
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
notify();
}
}
}

最佳答案

这段代码:

        t1.start(); 
synchronized(t1){

可能导致t1synchronized部分之前run。像这样解决这个问题:

        synchronized(t1){  
t1.start();

还有关于 sleep 的文档:

Causes the currently executing thread to sleep (temporarily cease execution) ...

使用此代码,事情看起来更清晰:

public class Calculate extends Thread {

public Calculate() {
}

@Override
public void run() {
synchronized (this) {
try {
System.out.println("Calc sleeping");
Thread.sleep(10000);
System.out.println("not supposed to be shown");
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
notify();
}
}
}

public class Supervisor {

public Supervisor() {
Calculate t1 = new Calculate();
System.out.println("Super " + Thread.currentThread().getName());
synchronized (t1) {
t1.start();
System.out.println("wait");
try {
System.out.println("Super waiting");
t1.wait(1000);
System.out.println("Super awake");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("finish");
}
}
}

打印:

Super main
wait
Super waiting
Calc sleeping
not supposed to be shown
Super awake
finish

看到,当 Supervisor hibernate 时,Calculate 被唤醒并运行完成,需要 10 秒,然后调用 notify 唤醒 Supervisor 继续。

关于java - 并行执行线程超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35436383/

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