Java中lock上锁 unlock解锁

代码很简短,本宝宝就径直上代码了,请喷吧!

/**
*jdk1.5后头出现了lock,创建锁不那么烦,调用lock上锁
unlock解锁,更加面向对象
*/
public class LockTest {

public static void main(String[] args) {
//运用其中类的方式实现runnable
new Thread( new Runnable() {
@Override
public void run(){
//调用out方法被之print方法
out pOut = new out();
pOut.print(“hello”);
}
//开启一个线程
}).start();
}
}

class out{
//调用lock的落实类renntrantlocak
Lock lock = new ReentrantLock();
public void print(String name){
//给当下之name上锁
lock.lock();
try {
//打印name的长度
for (int i = 0; i < name.length(); i++) {
System.out.println(name.charAt(i));
}
System.out.println();
}finally{
//解锁
lock.unlock();
}
}
}

 

打印:

h
e
l
l
o

相关文章