2020-11-28

用代码实现两个线程交替打印0-100的奇偶数

  1. 用synchronized关键字实现

/**

  • 用代码实现两个线程交替打印0-100的奇偶数,用synchronized关键字实现
    */

public class WaitNotifyPrintOddEvenSyn {
//2个线程
//一个处理偶数,一个处理奇数(使用位运算)
//用synchronized来通信
private static int count;
private static final Object lock =new Object();
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
while (count<100){
synchronized (lock){
//使用位运算 0代表偶数,1代表奇数
if((count & 1) == 0){
System.out.println(Thread.currentThread().getName()+":"+count++);
}
}
}
}
},"偶数").start();

 new Thread(new Runnable() {  @Override  public void run() {   while (count<100){    synchronized (lock){     //使用位运算 0代表偶数,1代表奇数     if((count & 1) == 1){      System.out.println(Thread.currentThread().getName()+":"+count++);     }    }   }  } },"奇数").start();}

}

  1. 使用wait/notify

/**

  • 两个线程交替打印0~100奇偶数,用wait/notify
    */
    public class WaitNotifyPrintOddEveWait {
    //1.拿到锁就打印
    //2.打印完,唤醒其他线程,就休眠
    private static int count =0;
    private static final Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
    Thread thread = new Thread(new TurningRunner(),"偶数");
    Thread thread1 = new Thread(new TurningRunner(),"奇数");
    thread.start();
    Thread.sleep(10);//稍作休眠,防止线程启动的顺序不一致
    thread1.start();
    }

    static class TurningRunner implements Runnable{
    @Override
    public void run() {
    while (count<=100){
    synchronized (lock){
    //拿到锁就打印
    System.out.println(Thread.currentThread().getName()+":"+count++);
    //只有两个线程,所以唤醒使用notify和notifAll 一样,唤醒那个睡眠的锁
    lock.notify();
    if(count<=100){
    try {
    //如果任务还没结束,就让出当前的锁,让自己去休眠
    lock.wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    }
    }
    }

}









原文转载:http://www.shaoqun.com/a/493299.html

联动优势电子商务:https://www.ikjzd.com/w/1921

蜜芽:https://www.ikjzd.com/w/1320

邓白氏集团:https://www.ikjzd.com/w/582


用synchronized关键字实现/**用代码实现两个线程交替打印0-100的奇偶数,用synchronized关键字实现*/publicclassWaitNotifyPrintOddEvenSyn{//2个线程//一个处理偶数,一个处理奇数(使用位运算)//用synchronized来通信privatestaticintcount;privatestaticfinalObjectlock=ne
韩蓬:韩蓬
vava:vava
火车票提前几个小时可以退?火车票退票时间是多少?:火车票提前几个小时可以退?火车票退票时间是多少?
康超:康超
(精品分析)亚马逊美国站游戏手柄类目市场调查数据报告:(精品分析)亚马逊美国站游戏手柄类目市场调查数据报告

No comments:

Post a Comment