mxllcf

导航

两个线程交替打印0——100的奇偶数(JAVA多线程)

使用两个线程去分别打印奇数和偶数,分别为奇数线程和偶数线程。

原理一是两个线程去竞争syn锁。

原理二是使用wait和notify方法来执行这个任务。

package threadcoreknowledge.threadbojectclasscomminmethods;

/**
 * @author leon
 * @描述  两个线程交替打印0~10的奇偶数,用synchronized关键字实现。
 */
public class WaitNotifyEddEvenSyn {
    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) {
                        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) {
                        if ((count & 1 ) != 0) {
                            System.out.println(Thread.currentThread().getName() + ":" + count++);
                        }
                    }
                }
            }
        }, "奇数线程").start();
    }
}

  

 

package threadcoreknowledge.threadbojectclasscomminmethods;

/**
 * @author leon
 * @描述 使用wait 和notify 来进行这个任务。
 */
public class WaitNotifyPrintOddEveWait {
    public static void main(String[] args) {
        new Thread(new TurningRunner(),"偶数").start();
        new Thread(new TurningRunner(),"奇数").start();
    }
    private static int count = 0;
    private  static final  Object lock = new Object();
    
    static class TurningRunner implements Runnable {
        @Override
        public void run() {
            while (count <= 100) {
                synchronized (lock) {
                    System.out.println(Thread.currentThread().getName() + ":" +
                            count++);
                    lock.notify();
                    if (count <= 100) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}

  

posted on 2021-10-19 20:00  mxllcf  阅读(501)  评论(0)    收藏  举报