gpt4 book ai didi

java - 我得到了以下代码片段的竞争条件

转载 作者:行者123 更新时间:2023-12-01 13:37:20 26 4
gpt4 key购买 nike

当ThreadA内的System.out.println未注释时,它运行良好。

竞争条件是否与System.out.println有关

要刷新到系统控制台是否需要时间并且运行良好。

如何解决这个问题才能顺利运行而不会中断

package com.test.concurrency;
class ThreadA extends Thread{
private int sum = 0;
@Override
public void run(){
synchronized (this) {
//System.out.println();
for(int i = 0; i<100 ;i++){
sum += i;
}
notify();
}
}
public int getSum(){
return sum;
}
}

public class WaitNNotify {
public static void main(String[] args) {
ThreadA t= new ThreadA ();
t.start();
System.out.println("Waiting for ThreadA to complete..."+Thread.currentThread().getName());
synchronized (t) {
try{
t.wait();

System.out.println("Finally the Thread is notified ... "+t.getSum());
}
catch (InterruptedException e) {
e.printStackTrace();
}
}


}

}

最佳答案

对于您的场景,您应该使用 join 而不是 wait-notify,以下是示例实现:

class ThreadA extends Thread {
private int sum = 0;

@Override
public void run() {
System.out.println();
for (int i = 0; i < 100; i++) {
sum += i;
}
}
public int getSum() {
return sum;
}
}

public class WaitNNotify {
public static void main(String[] args) {
ThreadA t = new ThreadA();
t.start();
System.out.println("Waiting for ThreadA to complete..."+ Thread.currentThread().getName());
try {
t.join();
System.out.println("Finally the Thread is completed ... "+ t.getSum());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

关于java - 我得到了以下代码片段的竞争条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21163891/

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