两个线程,一个线程打印1~52,另一个线程打印字母A-Z,打印顺序为12A34B56C……5152Z
2024-09-05 15:44:26
使用wait,notify实现
public class Test {
public synchronized void a() {
for (int i = 1; i <= 52; i++) {
System.out.print(i);
if (i % 2 == 0) {
notify();
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public synchronized void b() {
for (char i = 'A'; i <= 'Z'; i++) {
System.out.print(i);
notify();
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Test test = new Test();
new Thread(test::a).start();
new Thread(test::b).start();
}
}
使用condition实现
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class T {
Lock lock = new ReentrantLock();
Condition aa = lock.newCondition();
Condition bb = lock.newCondition();
public void a() {
lock.lock();
try {
for (int i = 1; i <= 52; i++) {
System.out.print(i);
if (i % 2 == 0) {
bb.signalAll();
try {
aa.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} finally {
lock.unlock();
}
}
public void b() {
lock.lock();
try {
for (char i = 'A'; i <= 'Z'; i++) {
System.out.print(i);
aa.signalAll();
try {
bb.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
T t = new T();
new Thread(t::a).start();
new Thread(t::b).start();
}
}
最新文章
- java中判断list是否为空的用法
- FFmpeg和X264的交叉编译环境
- python 使用__neg__和__iter__
- 以sysdba身份登录oracle报ORA-1031权限不足错误之完美分析
- mac 终端 svn 命令(转)
- Android:开发环境
- Qt Windows下开机自动启动自己的程序
- spark yarn任务的executor 无故 timeout之原因分析
- SSM
- HTML5学习笔记<;六>;: HTML5框架, 背景和实体
- React学习之路(二)
- BZOJ_3653_谈笑风生_树状数组
- 如何增加Ubuntu交换空间swap
- SSH 安全加固
- Struts2——通配符,Action Method_DMI
- IDEA的十大快捷键
- Node使用 Express框架,实现文件上传
- QT编译错误:member access into incomplete type &#39;QMouseEvent&#39;
- Javascript作用域学习笔记(三)
- git的使用(本地及关联远程,上传到远程)
热门文章
- Codeforces 1237E. Balanced Binary Search Trees
- 怎样设置 MySQL 远程连接
- 怎样理解 Vue 的 ";Hello, World!"; 代码?
- c# winfrom 界面设计
- dgv数据绑定后,添加行遇到过的问题并解决
- 10 Django之Ajax请求
- arcgisJs之featureLayer中feature的获取
- golang 环境变量讲解
- mysql精准模糊查询使用CONCAT加占位符(下划线“_”)的使用,直接限定了长度和格式
- zabbix4.2Proxy安装文档