面试题之开两个线程交替输出数字

java 设计一个类,要求两个线程分别交替输出正负整数:

public class printNumber implements Runnable { private int sign = 1; //1输出正数,-1输出负数 private static int seg = 1; //同步信号, 全局常量,所有线程共享 public printNumber(int sign) { this.sign = sign; } public void run() { for (int i=1; i<10; i++) { try { printNumber(i); } catch (Exception e) { e.printStackTrace(); }} } //同步方法 private synchronized void printNumber(int i) throws InterruptedException{ while (seg != sign) { wait(1000); } System.out.println(sign * i); seg = -1 * seg; } public static void main(String[] args) { printNumber p1 = new printNumber(1); printNumber p2 = new printNumber(-1); new Thread(p1).start(); new Thread(p2).start(); } }

输出结果: 【面试题之开两个线程交替输出数字】面试题之开两个线程交替输出数字
文章图片



    推荐阅读