gpt4 book ai didi

java - 在java中同步两个线程

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:47:31 25 4
gpt4 key购买 nike

我的 java 程序中有两个线程,一个是主线程,另一个线程是在主线程中生成的线程 A。现在我希望主线程启动线程 A 并等待直到线程 A 在 run 方法中执行了它的某些代码并且线程 A 应该挂起自己。然后主线程应该开始运行,运行几行代码,然后线程 A 应该从它停止的地方重新开始,反之亦然。这应该发生 n 次。我正在尝试如下:

线程A类:

public class ThreadA implements Runnable {
boolean suspended = false;
boolean stopped = false;
synchronized void stop() {
stopped = true;
suspended = false;
notify();
}
synchronized void suspend() {
suspended = true;
}
synchronized void resume() {
suspended = false;
notify();
}
void job() throws InterruptedException {
for (int i = 0; i < 5; i++)
synchronized (this) {
System.out.println("performing job.");
suspend();
while (suspended) {
notify();
suspended = false;
}
}
}
@Override
public void run() {
try {
job();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

主线程:

public class MainThread {
public static void main(String[] args) throws InterruptedException {
ThreadA a1=new ThreadA();
Thread t1=new Thread(a1);
synchronized (t1) {
t1.start();
for (int i = 0; i < 5; i++) {
t1.wait();
System.out.println("perform some action");
a1.resume();
}

}
}
}

预期输出:

performing job.
perform some action
performing job.
perform some action
performing job.
perform some action
performing job.
perform some action
performing job.
perform some action

实际输出:

performing job.
performing job.
performing job.
performing job.
performing job.
perform some action

我不知道为什么整个 for 循环都在线程 A 中执行,即使我已经在作业方法中发出了 notify() 信号。

最佳答案

这里有两个错误。

首先是你在同步和通知不同的对象。试试这个修改后的 main,我将 synchronized (t1) 更改为 synchronized (a1) 并将 t1.wait() 更改为 a1.wait()。

public static void main(String[] args) throws InterruptedException {
ThreadA a1=new ThreadA();
Thread t1=new Thread(a1);

synchronized (a1) { // CHANGED FROM t1 to a1
t1.start();
for (int i = 0; i < 5; i++) {
a1.wait(); // CHANGED FROM t1 to a1
System.out.println("perform some action");
a1.resume();
}

}
}

第二个错误是在 job() 方法中,它调用了 notify() 但没有调用 wait()。这是一个固定版本:

void job() throws InterruptedException {
for (int i = 0; i < 5; i++)
synchronized (this) {
System.out.println("performing job.");
suspend();
while (suspended) {
notify();
suspended = false;
wait(); // ADDED
}
}
}

我的测试运行的输出是

performing job.
perform some action
performing job.
perform some action
performing job.
perform some action
performing job.
perform some action
performing job.
perform some action

关于java - 在java中同步两个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24696246/

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