概述
开启双线程依次交替打印奇偶数,线程1只打印偶数,线程2只打印奇数。
尝试写这个算法的时候出现了一些问题,打印的数字在一千以内的时候时可以正常交替打印的。一旦打印的数字越来大的时候(七千左右),边出现数字不连贯的现象,如图:
修改后
修改前是没有Thread.sleep(1);
修改内容让当前线程睡(>1)毫秒,都可以正常依次打印的。目的是防止唤醒其他线程时,当前线程还未休眠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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50public int num = 0;
Object o = new Object();//锁对象
public void testOutNum() {
new Thread(new Runnable() {
public void run() {
synchronized (o) {//持有锁
for (; ; ) {
showNum(Thread.currentThread().getName(), num);
num++;
o.notifyAll();//唤起其他线程
try {
Thread.sleep(1);//防止唤醒其他线程时,当前线程还未休眠
o.wait();//当前线程休眠
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}, "Thread1:").start();
new Thread(new Runnable() {
public void run() {
synchronized (o) {
for (; ; ) {
showNum(Thread.currentThread().getName(), num);
num++;
o.notifyAll();
try {
Thread.sleep(1);
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}, "thread2:").start();
}
private void showNum(String name, int num) {
Log.e("Tag", name + ":----" + num);
}