首页 > 代码库 > 多线程篇八:线程锁

多线程篇八:线程锁

1.线程锁Lock/ReentrantLock

技术分享
package com.test.lock;

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

//线程锁,通常用于替换synchronized,比synchronized更加面向对象
public class LockTest {
    static class Outputer{
        Lock locks=new ReentrantLock();
        //方法1
        public void output1(String name){
            int len=name.length();
            locks.lock();//确保完整输出chenxiaobing后再输出donyanxia
            try{
                for(int i=0;i<len;i++){
                    System.out.print(name.charAt(i));
                }
                System.out.println();
            }finally{
                locks.unlock();//避免执行的代码发送异常,导致死锁,因此需要使用finally,无论执行是否成功,都进行解锁
            }
        }
    }
    public void init(){
        final Outputer o=new Outputer();
        
        //线程1
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    o.output1("chenxiaobing");
                }
            }
        }).start();
        
        //线程2
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    o.output1("donyanxia");
                }
            }
        }).start();
    }
    public static void main(String[] args) {
        new LockTest().init();
        //交替输出chenxiaobing、donyanxia
    }
}
View Code

 

多线程篇八:线程锁