两个线程交替打印偶数和奇数

第一种方法,使用 {Object#wait()},{Object#notify()}的方式

public class OldEvenTest {

    public static void main(String[] args) {
        //监视器对象
        Object monitor = new Object();
        new Thread(new EvenPrintTask(monitor), "偶数").start();
        new Thread(new OldPrintTask(monitor), "奇数").start();
    }


    static class OldPrintTask implements Runnable {

        private Object monitor;
        //奇数线程从1开始打印
        private int value = 1;

        public OldPrintTask(Object monitor) {
            this.monitor = monitor;
        }

        @Override
        public void run() {
            while (value <100) {
                synchronized (monitor) {
                    System.out.println(Thread.currentThread().getName() + ":" + value);
                    value += 2;
                    monitor.notify();
                    try {
                        monitor.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    static class EvenPrintTask implements Runnable {

        private Object monitor;
        //偶数对象
        private int value = 0;

        public EvenPrintTask(Object monitor) {
            this.monitor = monitor;
        }

        @Override
        public void run() {
            while (value <= 100) {
                synchronized (monitor) {
                    System.out.println(Thread.currentThread().getName() + ":" + value);
                    value += 2;
                    monitor.notify();
                    try {
                        monitor.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

注意:{Object#wait()},{Object#notify()}的调用必须要持有锁才行,否则会抛出IllegalMonitorStateException

偶数线程的run方法

@Override
public void run() {
    while (value <= 100) {
        synchronized (monitor) {
            System.out.println(Thread.currentThread().getName() + ":" + value);
            value += 2;
            monitor.notify();
            try {
                //打印出100以后,还是会继续等待直到其他线程唤醒当前线程。
                monitor.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

这种方式存在一个问题,就是偶数线程最终打印出100以后,还是会继续等待。我们修改一下偶数线程的run方法,当打印出100以后,就不再调用monitor.wait()方法。如下所示:

@Override
public void run() {
    while (value <= 100) {
        synchronized (monitor) {
            System.out.println(Thread.currentThread().getName() + ":" + value);
            value += 2;
            monitor.notify();
            try {
                //打印出100以后,不再等待,直接退出
                if (value <= 100) {
                    monitor.wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

第二种的方法,使用Lock+Condition的方式

private static int count = 0;

    private static void method2() {
        Lock lock = new ReentrantLock();
        Condition evenCondition = lock.newCondition();
        Condition oldCondition = lock.newCondition();
        //偶数线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count <= 100) {
                    try {
                        lock.lock();
                        System.out.println(Thread.currentThread().getName() + ":" + count);
                        count++;
                        //唤醒奇数线程
                        oldCondition.signal();

                        //打印出100后,就不再等待
                        if (count <= 100) {
                            evenCondition.await();
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        lock.unlock();
                    }
                }
            }
        }, "偶数").start();

        //奇数线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count <= 100) {
                    try {
                        lock.lock();
                        System.out.println(Thread.currentThread().getName() + ":" + count);
                        count++;
                        //唤醒偶数线程
                        evenCondition.signal();

                        oldCondition.await();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        lock.unlock();
                    }
                }
            }
        }, "奇数").start();
    }

第三种方法,使用并发包中的AtomicInteger和volatile修饰符组合

    //保证flag的线程可见性
    private static volatile Boolean flag = true;

    private static AtomicInteger num = new AtomicInteger();

    private static final Integer TOTAL = 100;

    private static void method3() {

        Thread jsThread = new Thread(new Runnable() {

            @Override
            public void run() {
                while (num.get() <= TOTAL - 1) {
                    if (!flag) {
                        System.out.println(Thread.currentThread().getName() + ": " 
                            + num.getAndIncrement());
                        flag = true;
                    }
                }
            }
        });

        jsThread.setName("奇数线程");

        Thread osThread = new Thread(new Runnable() {

            @Override
            public void run() {

                while (num.get() <= TOTAL) {
                    if (flag) {
                        System.out.println(Thread.currentThread().getName() + ":" 
                            + num.getAndIncrement());
                        flag = false;
                    }
                }
            }
        });

        osThread.setName("偶数线程");

        osThread.start();
        jsThread.start();

    }

参看链接

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、进程和线程 进程 进程就是一个执行中的程序实例,每个进程都有自己独立的一块内存空间,一个进程中可以有多个线程。...
    阿敏其人阅读 2,622评论 0 13
  • 【JAVA 线程】 线程 进程:是一个正在执行中的程序。每一个进程执行都有一个执行顺序。该顺序是一个执行路径,或者...
    Rtia阅读 2,783评论 2 20
  •   一个任务通常就是一个程序,每个运行中的程序就是一个进程。当一个程序运行时,内部可能包含了多个顺序执行流,每个顺...
    OmaiMoon阅读 1,706评论 0 12
  • 文章来源:http://www.54tianzhisheng.cn/2017/06/04/Java-Thread/...
    beneke阅读 1,525评论 0 1
  • Java多线程学习 [-] 一扩展javalangThread类 二实现javalangRunnable接口 三T...
    影驰阅读 2,987评论 1 18