两个多线程的交替打印
文章图片
文章图片
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
推荐阅读
- 放屁有这三个特征的,请注意啦!这说明你的身体毒素太多
- 爱就是希望你好好活着
- 昨夜小楼听风
- 知识
- 死结。
- 我从来不做坏事
- 烦恼和幸福
- 关于QueryWrapper|关于QueryWrapper,实现MybatisPlus多表关联查询方式
- Linux下面如何查看tomcat已经使用多少线程
- 说得清,说不清