• 多线程(JDK1.5的新特性互斥锁)


    多线程(JDK1.5的新特性互斥锁)(掌握)
    1.同步
    ·使用ReentrantLock类的lock()和unlock()方法进行同步
    2.通信
    ·使用ReentrantLock类的newCondition()方法可以获取Condition对象
    ·需要等待的时候使用Condition的await()方法, 唤醒的时候用signal()方法
    ·不同的线程使用不同的Condition, 这样就能区分唤醒的时候找哪个线程了
    举例:

    public static void main(String[] args) {
    final UnitTest ut = new UnitTest();
    Thread t1 = new Thread(new Runnable() {
    public void run() {
    while(true){
    ut.print1();
    }
    }
    });
    Thread t2 = new Thread(new Runnable() {
    public void run() {
    while(true){
    ut.print2();
    }
    }
    });
    Thread t3 = new Thread(new Runnable() {
    public void run() {
    while(true){
    ut.print3();
    }
    }
    });
    t1.start();
    t2.start();
    t3.start();
    }
    private ReentrantLock r =new ReentrantLock();
    Condition c1 = r.newCondition();
    Condition c2 = r.newCondition();
    Condition c3 = r.newCondition();
    private int flag = 1;

    public void print1() {

    r.lock();
    if(flag!=1){
    try {
    System.out.println("jinru 11");
    c1.await();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    System.out.println("11");
    flag=2;
    c2.signal();
    r.unlock();
    }
    public void print2() {
    r.lock();
    if(flag!=2){
    try {
    System.out.println("jinru 22");
    c2.await();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    System.out.println("22");
    flag=3;
    c3.signal();
    r.unlock();
    }
    public void print3() {
    r.lock();
    if(flag!=3){
    try {
    System.out.println("jinru 33");
    c3.await();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    System.out.println("33");
    flag=1;
    c1.signal();
    r.unlock();
    }

  • 相关阅读:
    JDBC事务管理
    JDBC常见操作
    Java集合之List接口
    Nginx+Keepalived+Lvs实现双机热备
    Nginx+Consul+Upsync实现动态负载均衡
    DNS域名解析概念
    WPF中实现两个窗口之间传值
    C# 重写(override)和覆盖(new)
    C# DateTime.Now函数
    WPF中在后台实现控件样式
  • 原文地址:https://www.cnblogs.com/756623607-zhang/p/6850840.html
Copyright © 2020-2023  润新知