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();
    
        }
    }
  • 相关阅读:
    Beta 冲刺day 6
    Beta冲刺day5
    Beta冲刺day4
    Beta 冲刺day3
    Beta 冲刺day2
    Beta冲刺day1
    Beta预备
    城市安全风险管理项目Postmortem结果
    项目总结
    Alpha冲刺置顶随笔
  • 原文地址:https://www.cnblogs.com/kaibing/p/9233415.html
Copyright © 2011-2022 走看看