zoukankan      html  css  js  c++  java
  • 线程通信(交替执行)

    package com.kaibing.thread;
    
    /**
     * 线程的通信
     * <p>
     * wati()
     * notify():随机唤醒一个
     * notifyAll():全部唤醒
     */
    class PrintNum implements Runnable {
    
        int num = 1;
    
        @Override
        public void run() {
            while (true) {
                synchronized (this) {
                    notify();
    
                    if (num <= 100) {
                        try {
                            Thread.currentThread().sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + ":" + num);
                        num++;
                    } else {
                        break;
                    }
    
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
    
            }
        }
    }
    
    public class Communication {
    
        public static void main(String[] args) {
            PrintNum p = new PrintNum();
            Thread t1 = new Thread(p);
            Thread t2 = new Thread(p);
    
            t1.setName("A");
            t2.setName("B");
    
            t1.start();
            t2.start();
    
        }
    }
  • 相关阅读:
    002-mybatis主配置文件
    001-mybatis框架
    mybatis学习
    tcp连接与释放
    浏览器输入url的全过程
    设备
    读写分离(三)
    读写分离(二)
    读写分离(一)
    主从复制(三)
  • 原文地址:https://www.cnblogs.com/kaibing/p/9233415.html
Copyright © 2011-2022 走看看