java - 线程1打印1-10,当线程打印到5后,线程2打印“hello”,然后线程1继续打印
2024-08-28 00:01:36
public class T { private static int a =1;//1代表线程1 2线程2 public static void main(String[] args) { final T t = new T(); new Thread(new Runnable() { @Override
public void run() {
synchronized (t) {
for(int i=1;i<=10;i++){
if(i==6){
try {
a=2;//切换线程2
t.wait();//线程1等待,并释放了对象的锁
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
}).start();; new Thread(new Runnable(){ @Override
public void run() {
synchronized (t) {
if(a!=2){//没有轮到,进入等待
try {
t.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("hello");
t.notifyAll(); } } }).start(); }
}
结果如下:
Thread-0:1
Thread-0:2
Thread-0:3
Thread-0:4
Thread-0:5
Thread-1:hello
Thread-0:6
Thread-0:7
Thread-0:8
Thread-0:9
Thread-0:10
最新文章
- webapi集成owin使用Oauth认证时能获取accee_token仍无法登录的解决办法
- Windows下MongoDB环境搭建
- map初始化定时器
- 谈谈文件增量同步算法:RSYNC和CDC
- reason: &#39;unable to dequeue a cell with identifier Cell
- 阿里开源Mysql分布式中间件:Cobar
- PHP文件上传处理
- Kubernetes DNS 简介
- NodeJS在线聊天室(NodeJS &; SocketIO &; Express &; EJS &; MongoDB &; Gulp)
- ASP.NET Core 2.0 自定义 _ViewStart 和 _ViewImports 的目录位置
- 【HTTP原理】TCP/IP三次握手和四次挥手
- Typescript 常见的几种函数重载方法详解与应用示例
- 学习笔记5—Python 将多维数据转为一维数组 (总结)
- kmp模式串匹配
- 关于requests.exceptions.SSLError: HTTPSConnectionPool
- Atitit 跨平台的系统截图解决方案
- uva 10983 Buy one, get the rest free 二分判定层次图
- WebSocket(二)-WebSocket、Socket、TCP、HTTP区别
- Python中参数多个值的表示法
- Spring mvc中@RequestMapping 6个基本用法小结