JAVA-基础语法-多线程基础-wait和notify
【摘要】 JAVA-基础语法-多线程基础-wait和notify
wait方法一定需要InterruptedException 异常捕获
在于wait()方法的执行机制非常复杂。首先,它不是一个普通的Java方法,而是定义在Object类的一个native方法,也就是由JVM的C代码实现的。其次,必须在synchronized块中才能调用wait()方法,synchronize锁住的对象就是 调用wait方法的对象,因为wait()方法调用时,会释放线程获得的锁,wait()方法返回后,线程又会重新试图获得锁。
this锁对象调用notify()方法,这个方法会随机唤醒一个(取决于操作系统)正在this锁等待的线程
notifyall() 则会唤醒所有在等待的线程。
package learn.basic.multi.thread;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author luzc
* @date 2020/6/30 9:43
* @desc
*/
public class Main {
public static void main(String[] args) throws InterruptedException {
TaskQueue q = new TaskQueue();
ArrayList<Thread> ts = new ArrayList<>();
for (int i=0; i<5; i++) {
Thread t = new Thread() {
public void run() {
// 执行task:
while (true) {
try {
String s = q.getTask();
System.out.println("execute task: " + s);
} catch (InterruptedException e) {
return;
}
}
}
};
t.start();
ts.add(t);
}
Thread add = new Thread(() -> {
for (int i=0; i<10; i++) {
// 放入task:
String s = "t-" + Math.random();
System.out.println("add task: " + s);
q.addTask(s);
try { Thread.sleep(100); } catch(InterruptedException e) {}
}
});
add.start();
add.join();
Thread.sleep(100);
for (Thread t : ts) {
t.interrupt();
}
}
}
class TaskQueue {
Queue<String> queue = new LinkedList<>();
public synchronized void addTask(String s) {
this.queue.add(s);
this.notifyAll();
}
public synchronized String getTask() throws InterruptedException {
while (queue.isEmpty()) {
this.wait();
}
return queue.remove();
}
}
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)