-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
62 lines (50 loc) · 1.22 KB
/
Copy pathMain.java
File metadata and controls
62 lines (50 loc) · 1.22 KB
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
package threadWait;
import java.util.LinkedList;
import java.util.Queue;
class TaskQueue{
final Queue<String> queue = new LinkedList<>();
public synchronized String getTask() throws InterruptedException{
while(this.queue.isEmpty()){
this.wait();
}//通常在while中wait
return queue.remove();
}
public synchronized void addTask(String name){
this.queue.add(name);
this.notifyAll();//唤醒全部等待线程
}
}
class WorkerThread extends Thread{
TaskQueue taskQueue;
public WorkerThread(TaskQueue taskqueue){
this.taskQueue = taskqueue;
}
public void run() {
while(!isInterrupted()){
String name;
try{
name = taskQueue.getTask();
} catch (InterruptedException e){
break;
}
String result = "Hello, " + name + " !";
System.out.println(result);
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
TaskQueue taskQueue = new TaskQueue();
WorkerThread worker = new WorkerThread(taskQueue);
worker.start();
taskQueue.addTask("bob");
Thread.sleep(1000);
taskQueue.addTask("alice");
Thread.sleep(1000);
taskQueue.addTask("tim");
Thread.sleep(1000);
worker.interrupt();
worker.join();
System.out.println("END");
}
}