经典笔试题:两个线程交替打印奇偶数
Posted Perry Blog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了经典笔试题:两个线程交替打印奇偶数相关的知识,希望对你有一定的参考价值。
一、采用对象的wait() notify()方法实现
package com.gaopeng.programming; import java.util.concurrent.TimeUnit; /** * 经典笔试题:交替打印奇偶数 采用对象的wait() notify()方法实现 * * @author gaopeng * */ public class OddEvenThread { private static volatile Integer counter = 0; public static Object monitor = new Object(); public static void main(String[] args) { Thread threadA = new Thread(new Runnable() { @Override public void run() { while (true) { // 获取monitor共享资源的监视器锁 synchronized (monitor) { System.out.println(counter++); try { monitor.notify(); monitor.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } }); Thread threadB = new Thread(new Runnable() { @Override public void run() { while (true) { // 获取monitor共享资源的监视器锁 synchronized (monitor) { System.out.println(counter++); try { monitor.notify(); monitor.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } }); threadA.start(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } threadB.start(); } }
二、采用volatile方法实现
package com.gaopeng.programming; import java.util.concurrent.TimeUnit; /** * 经典笔试题:交替打印奇偶数 采用volatile方法实现 * * @author gaopeng * */ public class OddEvenThreadVolatileVersion { private static volatile Integer counter = 0; private static volatile boolean loopForOdd = true; private static volatile boolean loopForEven = true; public static void main(String[] args) { Thread threadOdd = new Thread(new Runnable() { @Override public void run() { while (true) { if (loopForOdd) { System.out.println(counter++); loopForEven = false; } try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } }); Thread threadEven = new Thread(new Runnable() { @Override public void run() { while (true) { if (loopForEven) { System.out.println(counter++); loopForOdd = false; } try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } }); threadOdd.start(); threadEven.start(); } }
以上是关于经典笔试题:两个线程交替打印奇偶数的主要内容,如果未能解决你的问题,请参考以下文章