子父线程问题

本文介绍了一种使用Java实现的子父线程同步机制,通过synchronized关键字和wait/notify方法,确保子线程执行5次后,父线程执行3次,此过程循环10次。该机制展示了线程间如何进行有效的协调与控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建子父线程,保证子线程执行5次后,父线程执行3次 如此循环10次!
public class Test {
private boolean subFlag=true;//判断是主线程还是子线程 如果为true为子线程 false为主线程
public synchronized void sub(int loop){
    // 如果子线程不可执行,则当前线程等待
    if(!subFlag){
        try {
            this.wait();
        }catch (InterruptedException e){
            e.printStackTrace();
        }

    }
    for (int i=0;i<5;i++){
        System.out.println("loop:"+loop+"sub-"+Thread.currentThread().getName());

    }
    subFlag=false;
    this.notify();
}

public synchronized void min (int loop){
    if (subFlag){
        try {
            this.wait();
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
    for (int i=0;i<3;i++){
        System.out.println("loop:"+loop+"sub-"+Thread.currentThread().getName());
    }
    subFlag=true;
    this.notify();
}

}

public class Test2 {
public static void main(String[] args) {
Test2 t2 = new Test2();
t2.init();
}
public void init() {
final Test t = new Test();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
t.sub(i);
}
}
});
t1.start();
for (int i = 0; i < 10; i++) {
t.min(i);
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值