黑马程序员—学习日志,多线程关于3个线程轮流执行的问题。

<a href="http://edu.csdn.net/heima" target="blank">android培训</a>、<a href="http://edu.csdn.net/heima" target="blank">java培训</a>

看完多线程,毕老师讲到了2个线程之间轮流执行。但是怎么让3个多线程轮流执行呢?

下边让我们来分析一下代码。

JDK1.5中提供了多线程升级解决方案。


将同步synchronized替换成 实现LOCK操作

将Object 中的wait,notify,notifyAll,替换成Condition对象

该对象可以Lock锁,进行获取

该示例中实现了本方只唤醒对方的操作



import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Workkk {
public static void main(String[] args) {

final HomeWorkee h = new HomeWorkee();
new Thread() {
public void run() {
for (int i = 0; i < 3; i++)
try {
h.haha();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();

new Thread() {
public void run() {
for (int i = 0; i < 3; i++)
try {
h.hah();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();

new Thread() {
public void run() {
for (int i = 0; i < 3; i++)
try {
h.ha();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}

}

class HomeWorkee {
private int x = 1;
private int flag = 3; //标记为3,只能最先执行线程1


private Lock lock = new ReentrantLock(); // 实现锁的接口
/**
* 定义3个Condition
*/
private Condition condition_1 = lock.newCondition();
private Condition condition_2 = lock.newCondition();
private Condition condition_3 = lock.newCondition();

public void hah()throws InterruptedException {
lock.lock();
try {
if (flag == 1 ) {//线程1因为后边2个线程的短路判断,所以最先执行

condition_1.await();//线程1等待
}

System.out.println("线程1:" + x++);
System.out.println("线程1:" + x++);
System.out.println("线程1:" + x++);
System.out.println();

flag = 1;//执行完以后把标记置为1
condition_2.signal();//唤醒线程2
}finally{
lock.unlock();
}
}

public void haha() throws InterruptedException{
lock.lock();
try {
if (flag == 2 || flag == 3) {//因为flag初始值为3,所以即使线程抢到资源也不会执行,这样保证了线程按照顺序执行
condition_2.await();
}
System.out.println("线程2:" + x++);
System.out.println("线程2:" + x++);
System.out.println("线程2:" + x++);
System.out.println();
flag = 2;//置为2
condition_3.signal();//唤醒线程3

} finally {
lock.unlock();
}
}

public void ha() throws InterruptedException {
lock.lock();
try {
if (flag == 3 || flag == 1) {{//因为flag初始值为3,最先执行的1线程将标记改为2  所以即使线程抢到资源也不会执行,保证线程2优先线程3执行
condition_3.await();

}

System.out.println("线程3:" + x++);
System.out.println("线程3:" + x++);
System.out.println("线程3:" + x++);
System.out.println();

flag = 3;
condition_1.signal();//唤醒线程1
}finally{
lock.unlock();
}
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值