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”);
}
//开启3个线程
}).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

相关文章