Lock作用和synchronized关键字的作用类似:
public class Test5 {
public static void main(String[] args) {
new Test5().init();
}
private void init(){
final Outputer outputer = new Outputer();
new Thread(new Runnable() {
@Override
public void run() {
outputer.output("今天是一个好天气.");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
outputer.output("todayisverynice");
}
}).start();
}
}
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++){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print(name.charAt(i));
}
System.out.println();
} catch (Exception e) {
}finally{
//锁中间的语句必须用try语句扩起来并且在finally中释放锁对象,
//防止里面的语句发生异常,所对象永远不会释放
lock.unlock();
}
}
public synchronized void output2(String name){
int len = name.length();
for (int i=0; i<len; i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
public static synchronized void output3(String name){
int len = name.length();
for (int i=0; i<len; i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
}