Repository navigation
Expand file tree
/
Copy pathMyService.java
More file actions
52 lines (47 loc) · 2.02 KB
/
Copy pathMyService.java
File metadata and controls
52 lines (47 loc) · 2.02 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
package com.brianway.learning.java.multithread.lock.example3;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by Brian on 2016/4/15.
*/
public class MyService {
private ReentrantLock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
private boolean hasValue = false;
public void set() {
try {
lock.lock();
while (hasValue == true) {
System.out.println("有可能★★连续" + " 时间为" + System.currentTimeMillis() + " ThreadName=" + Thread.currentThread().getName());
condition.await();
}
System.out.println("打印★" + " 时间为" + System.currentTimeMillis() + " ThreadName=" + Thread.currentThread().getName());
hasValue = true;
//condition.signal();
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("set unlock" + " 时间为" + System.currentTimeMillis() + " ThreadName=" + Thread.currentThread().getName());
lock.unlock();
}
}
public void get() {
try {
lock.lock();
while (hasValue == false) {
System.out.println("有可能☆☆连续" + " 时间为" + System.currentTimeMillis() + " ThreadName=" + Thread.currentThread().getName());
condition.await();
}
System.out.println("打印☆" + " 时间为" + System.currentTimeMillis() + " ThreadName=" + Thread.currentThread().getName());
hasValue = false;
//condition.signal();
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("get unlock" + " 时间为" + System.currentTimeMillis() + " ThreadName=" + Thread.currentThread().getName());
lock.unlock();
}
}
}