前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Thread Object wait() notify()基本

Thread Object wait() notify()基本

作者头像
WindWant
发布2020-09-11 10:58:39
2690
发布2020-09-11 10:58:39
举报
文章被收录于专栏:后端码事
代码语言:javascript
复制
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();
                }
            }
        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-11-29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档