本文主要是介绍面试:双线程交替打印奇偶数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
代码如下:
package practice1;/*** 0-100的奇数偶数打印* 1、通过对象的wait和notify进行线程阻塞* 2、通过对num%2的结果进行奇数偶数的判断输出**/
public class JiOuOne {private static volatile int num = 0;private static final int max = 100;public static void main(String[] args) {String monitor = "monitor";// 偶数线程Thread oddThread = new Thread(new OddNumber(monitor));oddThread.setName("偶数打印:");// 奇数线程Thread evenThread = new Thread(new EvenNumber(monitor));evenThread.setName("奇数打印:");oddThread.start();evenThread.start();}/*** 打印偶数*/static class OddNumber implements Runnable {private String monitor;public OddNumber(String monitor) {this.monitor = monitor;}@Overridepublic void run() {while (num <= max) {synchronized (monitor) {// 如果num%2有余数,则除不尽,则阻塞while (num % 2 != 0) {try {monitor.wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.println(Thread.currentThread().getName() + "->" + num);num++;// 唤醒监视器monitor.notify();}}}}/*** 打印奇数*/static class EvenNumber implements Runnable {private String monitor;public EvenNumber(String monitor) {this.monitor = monitor;}@Overridepublic void run() {while (num < max) {synchronized (monitor) {// 如果num%2余数为0,则可以除尽,阻塞while (num % 2 == 0) {try {monitor.wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.println(Thread.currentThread().getName() + "->" + num);num++;// 唤醒对象监视器monitor.notify();}}}}}
运行结果:
这篇关于面试:双线程交替打印奇偶数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!