经典笔试题:两个线程交替打印1-100的整数
笔试题:
两个线程交替打印1-100的整数
题目说明:两个线程交替打印1-100的整数,一个打印奇数,一个打印偶数,要求输出结果有序。
。public class Test { private static volatile Integer counter = 1; private static volatile boolean flag = true; public static void main(String[] args) { Thread threadOdd = new Thread(new Runnable() { @Override public void run() { while (counter <= 100) { if (flag) { System.out.println(Thread.currentThread().getName() + " " + counter++); flag = false; } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }, "threadOdd"); Thread threadEven = new Thread(new Runnable() { @Override public void run() { while (counter <= 100) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } if (!flag) { System.out.println(Thread.currentThread().getName() + " " + counter++); flag = true; } } } }, "threadEven"); threadOdd.start(); threadEven.start(); } }
运行结果:
threadOdd 1
threadEven 2
threadOdd 3
threadEven 4
threadOdd 5
threadEven 6
threadOdd 7
threadEven 8
threadOdd 9
threadEven 10
threadOdd 11
threadEven 12
threadOdd 13
threadEven 14
threadOdd 15
threadEven 16
threadOdd 17
threadEven 18
threadOdd 19
threadEven 20
threadOdd 21
threadEven 22
threadOdd 23
threadEven 24
threadOdd 25
threadEven 26
threadOdd 27
threadEven 28
threadOdd 29
threadEven 30
threadOdd 31
threadEven 32
threadOdd 33
threadEven 34
threadOdd 35
threadEven 36
threadOdd 37
threadEven 38
threadOdd 39
threadEven 40
threadOdd 41
threadEven 42
threadOdd 43
threadEven 44
threadOdd 45
threadEven 46
threadOdd 47
threadEven 48
threadOdd 49
threadEven 50
threadOdd 51
threadEven 52
threadOdd 53
threadEven 54
threadOdd 55
threadEven 56
threadOdd 57
threadEven 58
threadOdd 59
threadEven 60
threadOdd 61
threadEven 62
threadOdd 63
threadEven 64
threadOdd 65
threadEven 66
threadOdd 67
threadEven 68
threadOdd 69
threadEven 70
threadOdd 71
threadEven 72
threadOdd 73
threadEven 74
threadOdd 75
threadEven 76
threadOdd 77
threadEven 78
threadOdd 79
threadEven 80
threadOdd 81
threadEven 82
threadOdd 83
threadEven 84
threadOdd 85
threadEven 86
threadOdd 87
threadEven 88
threadOdd 89
threadEven 90
threadOdd 91
threadEven 92
threadOdd 93
threadEven 94
threadOdd 95
threadEven 96
threadOdd 97
threadEven 98
threadOdd 99
threadEven 100