你的位置:
首页
>
软件开发 >
Java > Thread Object wait() notify()基本
Thread Object wait() notify()基本
发布时间:2016-11-29 18:02:15
package com.thread.test.thread;import java.util.ArrayDeque;import java.util.Queue;import java.util.concurrent.ThreadLocalRandom;/** * Create ...
package com.thread.test.thread;import java.util.ArrayDeque;import java.util.Queue;import java.util.concurrent.ThreadLocalRandom;/** * Created by windwant on 2016/11/29. */public class MyQueueSyn { public static void main(String[] args) throws InterruptedException { CR cr = new CR(); cr.addEle(String.valueOf(ThreadLocalRandom.current().nextInt(100))); cr.start(); new CRP(cr).start();// for (int i = 0; i < 100; i++) {// Thread.sleep(1000);// cr.addEle(String.valueOf(i * i));// if(i > ThreadLocalRandom.current().nextInt(100)) {// cr.tify();// }// System.out.println("mian thread add cr queue ele: " + i);// } }}class CRP extends Thread{ private CR cr; public CRP(CR t){ cr = t; } @Override public void run() { for (int i = 0; i < 100; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } cr.addEle(String.valueOf(i * i)); if(i > ThreadLocalRandom.current().nextInt(100)) { cr.tify(); } System.out.println("mian thread add cr queue ele: " + i); } }}class CR extends Thread{ public void addEle(String ele) { synchronized (queue) { queue.add(ele); } } public void tify(){ synchronized (queue){ queue.notify(); } } public Queue<String> queue = new ArrayDeque<>(); @Override public void run() { while (true){ synchronized (queue){ try { if(queue.size() == 0){ System.out.println("cr thread queue wait..."); queue.wait(); } Thread.sleep(1000); System.out.println("cr thread queue poll ele: " + queue.poll()); } catch (InterruptedException e) { e.printStackTrace(); } } } }}
原标题:Thread Object wait() notify()基本
关键词:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。