Java多线程常用Demo

两个线程交替打印奇偶数

使用synchronized、wait、notify

三个线程交替打印ABC

使用volatile实现状态变化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class ThreadABC extends Thread {
private volatile static int state = 0; // 利用state判断当前哪个线程应该打印
private static char[] list = new char[]{'A', 'B', 'C'};
private int type;

public ThreadABC(int type) {
this.type = type;
}

@Override
public void run() {
for (int i=0; i<10; ) {
if (state % 3 == type) {
System.out.println(list[type]);
state++;
i++;
}
}
}

public static void main(String[] args) {
new ThreadABC(0).start();
new ThreadABC(1).start();
new ThreadABC(2).start();
}
}

使用Lock与state状态

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2019-2021 子夜
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信