Skip to content

Commit a3a6b21

Browse files
committed
fix:面试遇到的题:多线程轮询打印
1 parent 09d71b3 commit a3a6b21

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

src/posts/项目/面试遇到的题.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,79 @@ public class ShowMeBug {
134134
```
135135
136136
## 多线程打印0-200
137+
系统学习多线程有感,再写这一题
138+
:::info
139+
多线程编程步骤:
140+
1. 创建资源类,在资源类中定义属性和方法
141+
2. 判断->干活->通知
142+
3. 创建多个线程调用资源类的方法
143+
:::
144+
```java
145+
class Share{
146+
private int num = 0;
147+
private boolean flag = true;
148+
public synchronized boolean print1() throws InterruptedException {
149+
//判断
150+
while(!flag && num <= 200){
151+
this.wait();
152+
}
153+
if(num > 200){
154+
//避免有未唤醒的线程导致永远无法结束
155+
notifyAll();
156+
return false;
157+
}
158+
//干活
159+
System.out.println(Thread.currentThread().getName() + "打印"+ num++);
160+
flag = false;
161+
//通知
162+
this.notifyAll();
163+
return true;
164+
}
165+
public synchronized boolean print2() throws InterruptedException {
166+
//判断
167+
while(flag && num <= 200){
168+
this.wait();
169+
}
170+
if(num > 200){
171+
notifyAll();
172+
return false;
173+
}
174+
//干活
175+
System.out.println(Thread.currentThread().getName() + "打印"+ num++);
176+
flag = true;
177+
//通知
178+
this.notifyAll();
179+
return true;
180+
}
181+
public synchronized int getNum(){
182+
return this.num;
183+
}
184+
}
185+
public class ConcurrentPrint {
186+
public static void main(String[] args) {
187+
Share share = new Share();
188+
new Thread(()->{
189+
while (true) {
190+
try {
191+
if (!share.print1()) break;
192+
} catch (InterruptedException e) {
193+
throw new RuntimeException(e);
194+
}
195+
}
196+
},"A").start();
197+
new Thread(()->{
198+
while(true){
199+
try {
200+
if (!share.print2()) break;
201+
} catch (InterruptedException e) {
202+
throw new RuntimeException(e);
203+
}
204+
}
205+
},"B").start();
137206

207+
}
208+
}
209+
```
138210
```java
139211
public class Main {
140212
private static final int MAX = 200;

0 commit comments

Comments
 (0)