java 多线程 day11 lock

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; /**
* Created by chengtao on 17/12/5.
* Lock 是替代 sycronized 的,相比sycronized 更加面向对象
* java.util.concurrent.locks.Lock;
* java.util.concurrent.locks.ReentrantLock;
*/
public class Thread1101_Lock { /**
* @param args
*/
public static void main(String[] args)throws Exception {
new Thread1101_Lock().init();
} private void init() throws Exception{
final Outputer outputer = new Outputer();
new Thread(new Runnable(){
public void run() {
while(true){
try {
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
outputer.output("zhangxiaoxiang");
} }
}).start(); new Thread(new Runnable(){
public void run() {
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output("lihuoming");
} }
}).start(); } static class Outputer{
Lock lock = new ReentrantLock();
public void output(String name){
int len = name.length();
lock.lock(); //和output1 对比 lock和synchronized的异同
try{
for(int i=0;i<len;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}finally{
lock.unlock(); //和output1 对比 lock和synchronized的异同
}
} /*
通过同步代码块来控制,注意锁对象一定要唯一
*/
public void output1(String name){
int len = name.length();
synchronized (Outputer.class) {
for(int i=0;i<len;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
} 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();
}
}
}
上一篇:[Codeforces Round #492 (Div. 1) ][B. Suit and Tie]


下一篇:varints