Java—线程锁技术

来源:互联网 发布:linux 限制ip ssh访问 编辑:程序博客网 时间:2024/06/05 17:11

先看代码

package cn.itcast.heima;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;import cn.itcast.heima.TraditionalThreadSynchronized.Outputer;public class LockTest {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubnew LockTest().init();//静态方法中不能new内部类的实例对象}private void init(){final  Outputer outputer = new Outputer();new Thread(new Runnable(){@Overridepublic void run() {// TODO Auto-generated method stubwhile(true){try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}outputer.output("ddddddddddddddd");}}}).start();new Thread(new Runnable(){@Overridepublic void run() {// TODO Auto-generated method stubwhile(true){try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}outputer.output("hhhhhhhhh");}}}).start();}static class Outputer{Lock lock = new ReentrantLock();         //获得锁public void output(String name){int len = name.length();lock.lock();                    //锁上try{for(int i=0;i<len;i++){System.out.print(name.charAt(i));}System.out.println();}finally{lock.unlock();                  //解锁}}}}
效果:


在使用Lock地方,需要try异常,因为就像我们进入厕所,如果晕在厕所里面,那我们出不来,人家也进不去!

0 0
原创粉丝点击