package com.thread;
/**
* 线程同步 ,子线程执行一次,主线程后在执行一次
* 大家轮流执行
*
* @author sky
*
*/
public class TraditionThread {
public static void main(String[] args) {
new TraditionThread().init();
}
public void init (){
final Business business = new Business();
// 直接重载父类的方法 子线程
new Thread(){
@Override
public void run() {
for (int i = 1; i <=3; i++) {
business.sub();
}
}
}.start();
// 主线程
for (int i = 1; i <=3; i++) {
business.main();
}
}
class Business {
private boolean isShouldSub = true; // true:子线程开始执行, false:主线程开始执行
public synchronized void sub (){
if (!isShouldSub){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 1; i <=2; i++) {
System.out.println("print sub ");
}
isShouldSub = false;
this.notify();
}
public synchronized void main (){
// true 等待
if (isShouldSub){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 1; i <= 3; i++) {
System.out.println("main");
}
// 执行完了之后,通知子线程执行
isShouldSub = true;
this.notify();
}
}
}
java 线程同步1 (传统方法)
最新推荐文章于 2025-07-22 09:27:55 发布
本文介绍了一个简单的线程同步示例,通过控制主线程与子线程的交替执行,实现资源的有效利用。通过`synchronized`关键字及`wait()`、`notify()`方法确保线程间的正确同步。
9万+

被折叠的 条评论
为什么被折叠?



