当前位置:网站首页>头歌 第3关:使用线程锁(Lock)实现线程同步
头歌 第3关:使用线程锁(Lock)实现线程同步
2022-06-25 21:59:00 【桂亭亭】
目录
编程要求
请仔细阅读右侧代码,根据方法内的提示,在Begin - End区域内进行代码补充。
测试说明
使得程序输出如下结果(因为线程的执行顺序是随机的可能需要你评测多次):
Thread-0得到了锁12345Thread-0释放了锁Thread-1得到了锁678910Thread-1释放了锁Thread-2得到了锁1112131415Thread-2释放了锁
这一关有点坑!!!
下面是我写出的代码自测有效一次即可过!
主要思路
在线程一运行时,让主线程休息一会,等待子线程执行完毕,再开启其他线程。
代码实现
package step3;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Task {
public static void main(String[] args) {
final Insert insert = new Insert();
Thread t1 = new Thread(new Runnable() {
public void run() {
insert.insert(Thread.currentThread());
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
insert.insert(Thread.currentThread());
}
});
Thread t3 = new Thread(new Runnable() {
public void run() {
insert.insert(Thread.currentThread());
}
});
// 设置线程优先级
// t1.setPriority(Thread.MAX_PRIORITY);
// t2.setPriority(Thread.NORM_PRIORITY);
// t3.setPriority(Thread.MIN_PRIORITY);
t1.start();
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
t3.start();
}
}
class Insert {
public static int num;
// 在这里定义Lock
private Lock lock = new ReentrantLock();
public void insert(Thread thread) {
/********* Begin *********/
if(lock.tryLock()){
try{
System.out.println(thread.getName()+"得到了锁");
for (int i = 0; i < 5; i++) {
num++;
System.out.println(num);
}
}finally{
System.out.println(thread.getName()+"释放了锁");
lock.unlock();
}
}else{
System.out.println(thread.getName()+"获取锁失败");
}
}
/********* End *********/
}
边栏推荐
- Oracle - data query
- Exclusive or operator simple logic operation a^=b
- What do l and R of earphone mean?
- ES6-Const常量与数组解构
- Idea shortcut
- Transformers load pre training model
- Equivalence class, boundary value, application method and application scenario of scenario method
- 【opencv450 samples】创建图像列表yaml
- Implementation of importing vscode from PDM
- Problem recording and thinking
猜你喜欢
随机推荐
牛客小白月赛52--E 分组求对数和(二分)
Es7/es9 -- new features and regularities
To solve the incompatibility between VM and device/credential guard, an effective solution for the whole network
The applet draws a simple pie chart
zabbix_ Server configuration file details
Thinking while walking
adb常用命令
异或运算符简单逻辑运算 a^=b
Determine whether the appointment time has expired
zabbix_server配置文件详解
ES6 -- 形参设置初始值、拓展运算符、迭代器、生成函数
干货丨产品的可行性分析要从哪几个方面入手?
论文笔记: 多标签学习 MSWL
Circuit module analysis exercise 5 (power supply)
提问的智慧?如何提问?
元宇宙标准论坛成立
最近准备翻译外国优质文章
ES6 -- formal parameter setting initial value, extension operator, iterator, and generating function
22 years of a doctor in Huawei
问题记录与思考








