gpt4 book ai didi

java - 同时通知两个线程

转载 作者:行者123 更新时间:2023-12-02 00:08:42 24 4
gpt4 key购买 nike

如何同时通知线程 t1 和线程 t2(因此首先获得 hey1hey2 的概率相同)?我尝试过notifyAll,但无法使其工作。

class Thr extends Thread
{
Thr () throws InterruptedException
{
Thread t1 = new Thread() {
public synchronized void run()
{
while (true)
{
try {
wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try
{
Thread.sleep(1500);
} catch (Exception e) { }
System.out.println("hey 1");
}
}
};

Thread t2 = new Thread() {
public synchronized void run()
{
while (true)
{
try {
wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try
{
Thread.sleep(1500);
} catch (Exception e) { }
System.out.println("hey 2");
}
}
};

t1.start();
t2.start();
}

public static void main(String args[]) throws InterruptedException
{
new Thr();
}
}

最佳答案

你应该wait在共享对象上并使用 notifyAll如:

class Thr extends Thread
{
Thr () throws InterruptedException
{
final Object lock = new Object ();

Thread t1 = new Thread() {
public void run()
{
try {
synchronized (lock) {
lock.wait();
}
} catch (InterruptedException e1) {
e1.printStackTrace();
}

System.out.println("hey 1");
}
};

Thread t2 = new Thread() {
public synchronized void run()
{
try {
synchronized (lock) {
lock.wait();
}
} catch (InterruptedException e1) {
e1.printStackTrace();
}

System.out.println("hey 2");
}
};

t1.start();
t2.start();
synchronized (lock) {
lock.notifyAll ();
}
}

public static void main(String args[]) throws InterruptedException
{
new Thr();
}
}

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

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