gpt4 book ai didi

java - 关于线程的wait()/notify

转载 作者:行者123 更新时间:2023-12-03 13:23:17 27 4
gpt4 key购买 nike

我试图写一个关于如何使用wait()和notify()的示例,但是似乎无法通知wait()

public class Transfer {
private int[] data;
private volatile int ptr;
private final Object lock = new Object();

public Transfer(int[] data) {
this.data = data;
this.ptr = 0;
}

public void send() {
while (ptr < data.length) {
synchronized (lock) {
try {
System.out.println("-----wait");
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
ptr++;
}
}
}

public void receive() {
while (ptr < data.length) {
synchronized (lock) {
System.out.println("current is " + data[ptr]);
System.out.println("-----notify");
lock.notifyAll();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
}

}

////in main()

int[] data = new int[] { 111, 222, 333, 444, 555, 666, 777, 888, 999, 000 };
Transfer tf = new Transfer(data);
Thread t1 = new Thread(() -> {
tf.receive();
});
Thread t2 = new Thread(() -> {
tf.send();
});
t2.start();
t1.start();
但结果是:
- - -等待
当前是111
- - -通知
当前是111
- - -通知
[无尽重复]
这不是我所期望的,应该是:
当前是111
当前是222 ...

最佳答案

class Transfer {
private int[] data;
private volatile int ptr;
private final Object lock = new Object();

public Transfer(int[] data) {
this.data = data;
this.ptr = 0;
}

public void send() {
while (ptr < data.length) {
synchronized (lock) {
try {
System.out.println("-----wait");
lock.notifyAll();
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
ptr++;
}
}
}

public void receive() {
while (ptr < data.length) {
synchronized (lock) {
System.out.println("current is " + data[ptr]);
System.out.println("-----notify");
try {
lock.notifyAll();
lock.wait();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
}

}
“Thread.sleep”不会释放锁定。因此,您需要“lock.wait”来释放该锁并让其他线程继续进行。然后,在“发送”增加指针后,它还应该发出通知,以便其他继续阻塞接收的线程现在可以继续进行。

关于java - 关于线程的wait()/notify,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64037595/

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