/*
1.A先做
2.A休息
3B做
4B唤醒A
5B休息
6A先告诉B我做累了,你再做所以先A.notify();
*/
public class BigOne {
//实现两个线程的交替运行 并且左脚永远先出去
public static void main(String[] args) {
RightThread r= new RightThread(); LeftThread l= new LeftThread(r);
l.start();
// r.start();
}
}
class X{ //资源共享 两个线程交替执行 为保证不发生并发错误 使用synchronized()
static Object obj =new Object();
}
class LeftThread extends Thread{
RightThread r;
public LeftThread(RightThread r) {
this.r=r;
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
synchronized(X.obj) {
r.start();
for(int i=0;i<6;i++) {
System.out.println("左脚"); //左脚先执行 然后休息下 此时 右脚抢到临界资源 开始执行
try {
X.obj.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //右脚休息后 从这里执行,然后 提醒右脚 等我累了 你再继续
X.obj.notify();
}
}
}
}
//2个线程在执行的时候 并不按照main方法中声明的顺序进行执行 争抢时间片 运行
class RightThread extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
synchronized(X.obj) {
for(int i=0;i<6;i++) {
System.out.println("由脚"); //右脚抢到临界资源 开始执行 累了 唤醒 左脚 然后休息
X.obj.notify(); // 唤醒 左脚
try {
X.obj.wait(); //然后休息
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
15、实现两个线程的交替运行 并且某一个操作永远先出去
最新推荐文章于 2024-08-12 16:47:32 发布