-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLockThread.java
More file actions
65 lines (58 loc) · 2.01 KB
/
LockThread.java
File metadata and controls
65 lines (58 loc) · 2.01 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
package com.thread;
import java.util.concurrent.locks.ReentrantLock;
/**
* 解决线程安全问题的方式三:Lock锁 --- JDK5.0新增
*
* 1. 面试题:synchronized 与 Lock的异同?
* 相同:二者都可以解决线程安全问题
* 不同:synchronized机制在执行完相应的同步代码以后,自动的释放同步监视器
* Lock需要手动的启动同步(lock()),同时结束同步也需要手动的实现(unlock())
*
* 2.优先使用顺序:
* Lock 同步代码块(已经进入了方法体,分配了相应资源) 同步方法(在方法体之外)
*
*
* 面试题:如何解决线程安全问题?有几种方式
*/
public class LockThread implements Runnable {
private int ticket = 100;
//实例化ReentrantLock
private ReentrantLock lcok = new ReentrantLock(true); //true:创建公平的Lock(先进先出)
@Override
public void run() {
while (true){
try {
//调用锁定方法
lcok.lock();
if (ticket > 0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":售票,票号为:" + ticket);
ticket--;
}else {
break;
}
}finally {
//调用解锁方法
lcok.unlock();
}
}
}
}
class LockTest{
public static void main(String[] args) {
LockThread w1 = new LockThread();
Thread t1 = new Thread(w1);
Thread t2 = new Thread(w1);
Thread t3 = new Thread(w1);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}