• JAVA线程通信


    wait()

    notify()

    notifyAll()

    1 只能用于synchronized 同步代码块和同步方法中

    2 这几个方法的调用者,必须是同一个同步监视器

    package com.LearnJava.Thread;
    
    import java.util.concurrent.locks.ReentrantLock;
    
    /*
        同步代码块
        synchronized(同步监视器){
            //需要同步的代码
        }
        同步监视器:俗称 锁,可以是任何实例化的类.但是需要共用同一个实例.
     */
    class WindowSell implements Runnable{
        ReentrantLock lock = new ReentrantLock();
        private int ticket = 100;
        @Override
        public void run() {
            while (true) {
                synchronized(this){
                    notify();
                    if (ticket > 0) {
                        System.out.println(Thread.currentThread().getName() + "sell " + ticket--);
    
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
    
                    }else{
                        break;
                    }
                }
    
            }
        }
    
    }
    public class ThreadTestTicket {
        public static void main(String[] args) {
            WindowSell win = new WindowSell();
            Thread t1 = new Thread(win);
            t1.setName("1号窗口");
            Thread t2 = new Thread(win);
            t2.setName("2号窗口");
            Thread t3 = new Thread(win);
            t3.setName("3号窗口");
    
            t1.start();
            t2.start();
            t3.start();
        }
    }
  • 相关阅读:
    软件RAID 0
    逻辑卷管理lvm
    磁盘配额quota
    合并 CentOS 6.8 的两个ISO镜像
    挂载mount
    非交互式添加分区
    磁盘分区-gdisk用法
    C博客作业01--分支、顺序结构
    C语言--第0次作业
    浅议正则表达式
  • 原文地址:https://www.cnblogs.com/superxuezhazha/p/12283684.html
Copyright © 2020-2023  润新知