通过join方法顺序执行多个线程
2024-10-20 05:37:54
方法一:直接用多线程之间的通讯去解决
package com.toov5.test; import javax.imageio.ImageTypeSpecifier; class Res1{
char flag = 'A' ;
} class A extends Thread{ Res1 res;
public A(Res1 res) {
this.res=res;
}
@Override
public void run() { while (true) {
synchronized (res) {
if (res.flag == 'A') {
System.out.println("A");
res.flag='B';
res.notifyAll();
}else {
try {
res.wait();
} catch (Exception e) {
e.printStackTrace();
} }
}
} } } class B extends Thread{
Res1 res;
public B(Res1 res) {
this.res=res;
} @Override
public void run() {
while (true) {
synchronized (res) {
if (res.flag == 'B') {
System.out.println("B");
res.flag='C';
res.notifyAll();
}else {
try {
res.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
} } class C extends Thread{
Res1 res;
public C(Res1 res) {
this.res=res;
} @Override
public void run() {
while (true) {
synchronized (res) {
if (res.flag == 'C') {
System.out.println("C");
res.flag='D';
}else {
try {
res.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
} } public class Test9 { public static void main(String[] args) {
Res1 res1 = new Res1();
A a = new A(res1);
B b = new B(res1);
C c = new C(res1);
a.start();
b.start();
c.start(); } }
方法二:join()去执行
public class JoinThreadDemo02 {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
public void run() {
System.out.println("A");
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
t1.join();
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("B");
}
});
Thread t3 = new Thread(new Runnable() {
public void run() {
try {
t2.join();
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("C");
}
});
t1.start();
t2.start();
t3.start();
}
}
解读:三个线程在交替执行,被cpu去调度。 如果调度的是t3 那么执行的是 t2.join() 此时t2线程又是跑了 t1.join(),一次类推、
总之 三个线程去调度时候 都是不确定的 每次的调度都是套着环在里面 每种可能性都有了设计
我喜欢这样的代码
最新文章
- CRL快速开发框架系列教程七(使用事务)
- NetworkComms 文件上传下载和客户端自动升级(非开源)
- 关闭Eclipse的控制台console自动跳出
- 转:如何学习SQL(第四部分:DBMS扩展功能与SQL高级话题)
- zoj 2760 How Many Shortest Path 最大流
- Qt中使用cout, cin, cerr
- document.body.scrollTop与document.documentElement.scrollTop兼容
- i春秋与我
- 如何为ubuntu server 版本 安装图形界面
- 利用data-src属性 更换图片
- LINUX_正则表达式
- 正则匹配报文中的XML(HTML)标签,替换重新输出
- 运行android模拟器,emulator: ERROR: x86 emulation currently requires hardware acceleration!
- 开源微信Http协议Sdk【实现登录/获取好友列表/修改备注/发送消息】
- [Err] 1111 - Invalid use of group function
- python-day6---流程控制
- KCP 传输协议
- 在LaTeX中配置西夏文字体与环境
- 【原创】由于python的导入方式引起的深坑
- 利用sys.dm_db_index_physical_stats查看索引碎片等数据
热门文章
- python 中NumPy和Pandas工具包中的函数使用笔记(方便自己查找)
- Gson和Fastjson的使用
- idea Plugin ";Maven Integration Extension"; was not loaded: required plugin ";Maven Integration"; is disabled
- jqgrid 事件说明
- Kotlin——初级篇(四):控制语句详解
- java 序列化的作用
- CSS:text-decoration参数说明
- h5 localStorage本地存储
- 【Java工程师之路】[1-2.2]Java10个面向对象设计原则
- Spring Cloud架构