public class MyThread {
public static void main(String[] args) {
final Bus bus=new Bus();
new Thread(()->{
for (int i = 0; i < 3; i++) {
bus.subMethod();
}
},"子线程").start();
/**
* 主线程
*/
for (int i = 0; i < 3; i++) {
bus.mainMethod();
}
}
}
class Bus{
private boolean subFlag=true;
public synchronized void mainMethod(){
while (subFlag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()+"main方法-->"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
subFlag=true;
notify();
}
public synchronized void subMethod(){
while (!subFlag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()+"---->"+i);
}
subFlag=false;
notify();
}
}
两个线程交替打印3次(每次运行5次)
最新推荐文章于 2023-05-25 13:35:53 发布