这是我的示例代码。
class A implements Runnable{
//stuff
Thread thr = new Thread(this);
boolean flag;
public void run()
{
while(true){
if(condition)flag = true;
}
}
}
class B implements Runnable{
//stuff
A a = new A();
Thread thr = new Thread(this);
public void run()
{
while(true){
//i ll do some thing here
if(a.flag == true)System.out.println("Kaboom");
}
}
public static void main(String[] args)
{
B b = new B();
}
}
所以事情是我在 a 之前启动 b,我希望 b 等到 a.flag == true 来触发“Kaboom”,而 a.thr 必须等待 b 在 run() 方法中完成它的工作。我试过了,但没用
class A implements Runnable{
//stuff
Thread thr = new Thread(this);
boolean flag;
public void run()
{
while(true){
if(condition)flag = true;
synchronized(B.class){
this.flag=true;
B.class.notifyAll();
}
}
}
}
class B implements Runnable{
//stuff
A a = new A();
Thread thr = new Thread(this);
public void run()
{
while(true){
synchronized(this){
while(a.flag!=true)
{
this.wait();
}}
}
}
public static void main(String[] args)
{
B b = new B();
}}
我的同步块(synchronized block)肯定有问题,但我不知道是什么。
这可能是一个愚蠢的问题,但我只是 JAVA 的初学者,我并没有真正了解那些 Thread 的东西以及它是如何工作的。请帮助我
最佳答案
我喜欢您使用 wait/notifyAll 使线程在满足恢复运行的条件之前不使用 CPU 的原始方法。这是一个保持这种方法的解决方案。
一些注意事项:
1 - 在类对象上同步时要小心。除非你真的想同步整个类,否则创建一个对象并将其用作锁。
2 - 使用 volatile
关键字确保 Java 不会创建变量的线程本地版本,并且对其值的更改会立即反射(reflect)到其他线程。
public class Threads {
private final Object lock = new Object();
private volatile boolean flag;
class RunnableA implements Runnable {
private volatile boolean condition = false;
@Override
public void run() {
while (true) {
if (condition) {
if (!flag) {
synchronized (lock) {
System.out.println("Setting Flag to True");
flag = true;
lock.notifyAll();
}
}
} else {
System.out.println("Condition is False");
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
}
}
}
}
}
class RunnableB implements Runnable {
@Override
public void run() {
while (true) {
while (flag == false) {
synchronized (lock) {
if (flag == false) {
try {
lock.wait();
} catch (InterruptedException ex) {
}
}
}
}
System.out.println("Kaboom");
}
}
}
public void run() {
RunnableA runnableA = new RunnableA();
RunnableB runnableB = new RunnableB();
Thread t1 = new Thread(runnableA);
Thread t2 = new Thread(runnableB);
t1.start();
t2.start();
try {
Thread.sleep(5000L);
} catch (InterruptedException ex) {
}
runnableA.condition = true;
}
public static void main(String[] args) {
new Threads().run();
}
}
关于java - 如何让两个线程等待对方的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33841876/