zoukankan      html  css  js  c++  java
  • Thread Object wait() notify()基本

    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();
                    }
                }
            }
        }
    }
  • 相关阅读:
    java 中 堆、栈的区别(转)
    斐波那契数列(关于递归)
    .NetCore使用Hangfire
    大话西游系统文件分析
    VC游戏开发图片镂空
    华硕XTion Pro开发环境配置
    TweenMax 参数说明(中文翻译)
    程序员的追求
    最近得到的
    mvc的json
  • 原文地址:https://www.cnblogs.com/niejunlei/p/6114435.html
Copyright © 2011-2022 走看看