当前位置: 首页 » 产品 » 电子五金 » 正文

java多线程中的锁的几种用法总结(必看)

放大字体  缩小字体 发布日期: 2024-11-28 04:42   来源:http://www.baidu.com/  作者:无忧资讯  浏览次数:28
核心提示:package com.ietree.basicskill.mutilthread.lock;import java.util.concurrent.locks.Condition;import java.util.concurrent.l

package com.ietree.basicskill.mutilthread.lock;

import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class UseManyCondition { private ReentrantLock lock=new ReentrantLock(); private Condition c1=lock.newCondition(); private Condition c2=lock.newCondition(); public void m1(){ try { lock.lock(); System.out.println("当前线程:" +Thread.currentThread().getName() + "进入方法m1等待.."); c1.await(); System.out.println("当前线程:" +Thread.currentThread().getName() + "方法m1继续.."); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public void m2(){ try { lock.lock(); System.out.println("当前线程:" +Thread.currentThread().getName() + "进入方法m2等待.."); c1.await(); System.out.println("当前线程:" +Thread.currentThread().getName() + "方法m2继续.."); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public void m3(){ try { lock.lock(); System.out.println("当前线程:" +Thread.currentThread().getName() + "进入方法m3等待.."); c2.await(); System.out.println("当前线程:" +Thread.currentThread().getName() + "方法m3继续.."); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public void m4(){ try { lock.lock(); System.out.println("当前线程:" +Thread.currentThread().getName() + "唤醒.."); c1.signalAll(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public void m5(){ try { lock.lock(); System.out.println("当前线程:" +Thread.currentThread().getName() + "唤醒.."); c2.signal(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public static void main(String[] args) { final UseManyCondition umc=new UseManyCondition(); Thread t1=new Thread(new Runnable() { @Override public void run() { umc.m1(); } },"t1"); Thread t2=new Thread(new Runnable() { @Override public void run() { umc.m2(); } },"t2"); Thread t3=new Thread(new Runnable() { @Override public void run() { umc.m3(); } },"t3"); Thread t4=new Thread(new Runnable() { @Override public void run() { umc.m4(); } },"t4"); Thread t5=new Thread(new Runnable() { @Override public void run() { umc.m5(); } },"t5"); t1.start(); // c1 t2.start(); // c1 t3.start(); // c2 try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } t4.start(); // c1 try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } t5.start(); // c2 } }

 
 
[ 产品搜索 ]  [ 加入收藏 ]  [ 告诉好友 ]  [ 打印本文 ]  [ 违规举报 ]  [ 关闭窗口 ]

 

 
推荐图文
推荐产品
点击排行
    行业协会  备案信息  可信网站