两个多线程的交替打印

两个多线程的交替打印
文章图片
两个多线程的交替打印
文章图片

package cn.thread; public class ManyThread { public static void main(String[] args) { Object obj = new Object(); new Thread(new MyHandler1(obj), "t1").start(); new Thread(new MyHandler2(obj), "t2").start(); } }class MyHandler1 implements Runnable { Object obj; int count = 1; public MyHandler1(Object obj) { this.obj = obj; }@Override public void run() { for (int i = 1; i < 10; i++) { synchronized (obj) { try { // if (count % 2 == 1) {// 打印所有的奇数 System.out.println(Thread.currentThread().getName() + "__count=" + count); count += 2; if (i < 9) { obj.notify(); obj.wait(); Thread.sleep(300); }else{ obj.notify(); Thread.sleep(300); } } catch (InterruptedException e) { e.printStackTrace(); } } } } }class MyHandler2 implements Runnable { Object obj; int count = 2; public MyHandler2(Object obj) { this.obj = obj; }@Override public void run() { for (int i = 1; i < 10; i++) { synchronized (obj) { try {System.out.println(Thread.currentThread().getName() + "__count=" + count); count += 2; if (i < 9) { obj.notify(); obj.wait(); Thread.sleep(300); }else{ obj.notify(); Thread.sleep(300); } } catch (InterruptedException e) { e.printStackTrace(); } } } } }

两个多线程的交替打印
【两个多线程的交替打印】转载于:https://www.cnblogs.com/1020182600HENG/p/6044654.html

    推荐阅读