使用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();
}
}

最新文章

  1. java中判断list是否为空的用法
  2. FFmpeg和X264的交叉编译环境
  3. python 使用__neg__和__iter__
  4. 以sysdba身份登录oracle报ORA-1031权限不足错误之完美分析
  5. mac 终端 svn 命令(转)
  6. Android:开发环境
  7. Qt Windows下开机自动启动自己的程序
  8. spark yarn任务的executor 无故 timeout之原因分析
  9. SSM
  10. HTML5学习笔记&lt;六&gt;: HTML5框架, 背景和实体
  11. React学习之路(二)
  12. BZOJ_3653_谈笑风生_树状数组
  13. 如何增加Ubuntu交换空间swap
  14. SSH 安全加固
  15. Struts2——通配符,Action Method_DMI
  16. IDEA的十大快捷键
  17. Node使用 Express框架,实现文件上传
  18. QT编译错误:member access into incomplete type &#39;QMouseEvent&#39;
  19. Javascript作用域学习笔记(三)
  20. git的使用(本地及关联远程,上传到远程)

热门文章

  1. Codeforces 1237E. Balanced Binary Search Trees
  2. 怎样设置 MySQL 远程连接
  3. 怎样理解 Vue 的 &quot;Hello, World!&quot; 代码?
  4. c# winfrom 界面设计
  5. dgv数据绑定后,添加行遇到过的问题并解决
  6. 10 Django之Ajax请求
  7. arcgisJs之featureLayer中feature的获取
  8. golang 环境变量讲解
  9. mysql精准模糊查询使用CONCAT加占位符(下划线“_”)的使用,直接限定了长度和格式
  10. zabbix4.2Proxy安装文档