-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain3.java
More file actions
78 lines (65 loc) · 1.53 KB
/
Copy pathMain3.java
File metadata and controls
78 lines (65 loc) · 1.53 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package concurrentLock;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class TaskQueue{
final Queue<String> queue = new LinkedList<>();
final Lock lock = new ReentrantLock();
final Condition notEmpty = lock.newCondition();
public String getTask() throws InterruptedException{
lock.lock();
try{
while(this.queue.isEmpty()){
notEmpty.await();
}
return queue.remove();
} finally {
lock.unlock();
}
}
public void addTask(String name){
lock.lock();
try {
this.queue.add(name);
notEmpty.signalAll();//唤醒全部等待线程
} finally{
lock.unlock();
}
}
}
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 Main3 {
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");
}
}