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();
            }
        }
    }

    运行结果:

  • 相关阅读:
    checkListbox的单选
    IP地址控件CIPAddressCtrl类的使用
    C++ Socket编程步骤
    环形缓冲区
    隐式链接和显示链接的区别
    memset、memcpy的使用方法!
    cetlm下载地址
    安装 GCC
    centos 配置代理
    make软件包安装
  • 原文地址:https://www.cnblogs.com/trnanks/p/11517954.html
Copyright © 2011-2022 走看看