Java多线程——100以内奇数偶数交替打印(学习笔记)

it2023-07-12  65

package com.sgg.thread; public class ThreadTest03 { //处理类 public static class Handler { public int value = 1; //初始值 public boolean odd = true; //奇数 } public static Handler handler = new Handler(); // 奇数线程类 public static class PrintOdd implements Runnable { @Override public void run() { while (handler.value <= 100) { synchronized (handler) { if (handler.odd) { //如果是奇数 System.out.println(Thread.currentThread().getName() + "-->" + handler.value); handler.value++; handler.odd = !handler.odd; handler.notify(); //唤醒偶数线程 } else { try { handler.wait(); //交出锁 } catch (InterruptedException e) { e.printStackTrace(); } } } } } } // 偶数线程类 public static class PrintEven implements Runnable { @Override public void run() { while (handler.value <= 100) { synchronized (handler) { if(handler.odd){ try { handler.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } else { System.out.println(Thread.currentThread().getName() + "-->" + handler.value); handler.value++; handler.odd = !handler.odd; handler.notify(); //唤醒奇数线程 } } } } } // 运行主类 public static void main(String[] args) { Thread oddThread = new Thread(new PrintOdd()); Thread evenThread = new Thread(new PrintEven()); oddThread.setName("oddThread"); evenThread.setName("evenThread"); oddThread.start(); evenThread.start(); } }

输出结果:

最新回复(0)