子线程执行10次后,主线程再运行5次,这样交替执行三遍
# 子线程执行10次后,主线程再运行5次,这样交替执行三遍
package com.itheima.gan;
/**
* 子线程执行10次后,主线程再运行5次,这样交替执行三遍
* @author 12428
*
*/
public class Test {
public static void main(String[] args) {
final Bussiness bussiness=new Bussiness();
//创建一个子线程,run方法里面子线程执行3变
new Thread(new Runnable() {
public void run() {
for(int i=0;i<3;i++) {
bussiness.subMethod();
}
}
}).start();
//主线程
for(int i=0;i<3;i++) {
bussiness.mainMethod();
}
}
}
class Bussiness{
//创建一个私有的标识位
private boolean subFlag=true;
public synchronized void mainMethod() {
while(subFlag) {
try {
//标识为true 就等待,释放所持有的锁,让另一个线程执行,直到被唤醒才继续执行下去
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果当前的标志位不为true
//就向下执行
for(int i=0;i<5;i++) {
System.out.println(Thread.currentThread().getName()+" : main thread running loop count --"+i);
try {
//线程休眠1s,再执行
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//执行完上面的循环后再把标志位改为true,防止这个线程两次连续执行
subFlag=true;
notify();
}
public synchronized void subMethod() {
//如果标识位为false
//就执行等待,让另一个线程执行,直到被唤醒
while(!subFlag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果标识为true
//向下执行
for(int i=0;i<10;i++) {
System.out.println(Thread .currentThread().getName()+" : sub thread runnig loop count -- "+i);
//每执行一次就休眠1s
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//执行完一个循环后就将标识为改为false,防止这个线程连续两次执行
subFlag=false;
notify();
}
}
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
编辑 (opens new window)
上次更新: 2024/01/26, 05:03:22
- 01
- python使用生成器读取大文件-500g09-24
- 02
- Windows环境下 Docker Desktop 安装 Nginx04-10
- 03
- 使用nginx部署多个前端项目(三种方式)04-10