Java 3个或3个以上的线程通信


上一个帖子中简单的表示了两个线程之间的通信,但如果有三个线程或以上还能用类似的方法吗?通过再增加一个print3的方法,再加一个线程来让三个线程顺序执行呢,直接说结果:不行!

因为notify()方法是随机唤醒一个等待中的线程,当有两个线程在等待的时候,只会随机的唤醒其中的一个,被唤醒的线程就会绕过判断flag变量的判断,执行其他的顺序了,那么三个线程肯定不能的顺序执行了。

这时候就要用另一个唤醒方法了notifyAll(),此方法会唤醒所有在等待的线程,Printer类里print()方法内的flag变量判断从if改为while,因为等待的线程是随机被唤醒的,如果flag变量不匹配方法就应该继续是等待的状态。

public class Test {

    public static void main(String[] args) {
        final Printer printer = new Printer();

        new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    try {
                        printer.print1();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    try {
                        printer.print2();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    try {
                        printer.print3();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

}

class Printer {

    private int flag = 1;

    public void print1() throws Exception {
        synchronized(this) {
            while (flag != 1) {
                this.wait();
            }
            System.out.println(Thread.currentThread().getName() + " : 11111");
            flag = 2;
            this.notifyAll();
        }
    }

    public void print2() throws Exception {
        synchronized(this) {
            while (flag != 2) {
                this.wait();
            }
            System.out.println(Thread.currentThread().getName() + " : 22222");
            flag = 3;
            this.notifyAll();
        }
    }

    public void print3() throws Exception {
        synchronized(this) {
            while (flag != 3) {
                this.wait();
            }
            System.out.println(Thread.currentThread().getName() + " : 33333");
            flag = 1;
            this.notifyAll();
        }
    }
}

JDK1.5的新特性互斥锁

问题来了:这样做岂不是麻烦的很?

在1.5版本后有个新特征,叫互斥锁ReentrantLock,可以唤醒指定的线程。

用法:

  • (1)同步
    • 使用ReentrantLock类的lock()unlock()方法进行同步
  • (2)通信
    • 使用ReentrantLock类的newCondition()方法可以获取Condition对象。
    • 需要等待的时候使用Conditionawait()方法, 唤醒的时候用signal()方法。
    • 不同的线程使用不同的Condition, 这样就能区分唤醒的时候找哪个线程了。
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Test {

    public static void main(String[] args) {
        final Printer printer = new Printer();

        new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    try {
                        printer.print1();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    try {
                        printer.print2();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    try {
                        printer.print3();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

}

class Printer {

    private ReentrantLock r = new ReentrantLock();
    private Condition c1 = r.newCondition();
    private Condition c2 = r.newCondition();
    private Condition c3 = r.newCondition();

    private int flag = 1;

    public void print1() throws Exception {
        r.lock();
            if (flag != 1) {
                c1.await();
            }
            System.out.println(Thread.currentThread().getName() + " : 11111");
            flag = 2;
            c2.signal();
        r.unlock();
    }

    public void print2() throws Exception {
        r.lock();
            if (flag != 2) {
                c2.await();
            }
            System.out.println(Thread.currentThread().getName() + " : 22222");
            flag = 3;
            c3.signal();
        r.unlock();
    }

    public void print3() throws Exception {
        r.lock();
            if (flag != 3) {
                c3.await();
            }
            System.out.println(Thread.currentThread().getName() + " : 33333");
            flag = 1;
            c1.signal();
        r.unlock();
    }
}

因为可以调用指定的Condition对象唤醒线程,所以可以把while改成if



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值