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

}

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/lx1258/p/14051958.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!