zoukankan      html  css  js  c++  java
  • 两个线程交替打印奇数和偶数

    public class ThreadTest {
        public static void main(String[] args) {
            Thread evenThread = new Thread(new PrintEven(),"打印奇数");
            Thread oddThread = new Thread(new PrintOdd(),"打印偶数");
            evenThread.start();
            oddThread.start();
        }
    }
    
    class Count{
        public static final Object lock = new Object();
    }
    
    class PrintEven implements Runnable{
        @Override
        public void run() {
            synchronized (Count.lock) {
                for(int i = 1; i < 10; i += 2) {
                    System.out.println(Thread.currentThread().getName() + " : " + i);
                    Count.lock.notifyAll();
                    try {
                        Count.lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Count.lock.notifyAll();
            }
        }
    }
    
    class PrintOdd implements Runnable{
        @Override
        public void run() {
            synchronized (Count.lock) {
                for(int i = 2; i < 10; i += 2) {
                    System.out.println(Thread.currentThread().getName() + " : " + i);
                    Count.lock.notifyAll();
                    try {
                        Count.lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Count.lock.notifyAll();
            }
        }
    }

    运行结果:

  • 相关阅读:
    shell文件包含
    shell输入/输出重定向
    shell流程控制
    shell echo命令(六)
    shell基本运算符(五)
    shell数组(四)
    shell传递参数-$的用法(三)
    SQL 注入 处理
    WPF 还未开始我就打算结束
    Java SDK 2.0
  • 原文地址:https://www.cnblogs.com/trnanks/p/11517954.html
Copyright © 2011-2022 走看看