线程之Lock
import java.util.concurrent.locks.ReentrantLock;
public class ThreadLock {
/**
* java中的鎖類是于synchronized
* Lock是比傳統線程模型中的synchronized 的方式更加面向對象,與生活中的鎖類似
* 鎖本身也是一個對象。兩個線程執行的飛、代碼片段要實現同步互斥的效果
* 他們必須是同一個對象。鎖是上在代表要操作的資源的類的內部方法中,而不是線程代碼中
*/
public static void main(String[] args) {
final Outputer outputer = new Outputer();
new Thread(new Runnable(){
@Override
public void run() {
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output("123456789");
}
}
}).start();
new Thread(new Runnable(){
@Override
public void run() {
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output("abcdefg");
}
}
}).start();
}
}
class Outputer{
Lock lock = new ReentrantLock();
public void output(String string){
int length = string.length();
lock.lock();
//防止在解鎖之前發生異常,異常使程序終止,而沒有解鎖,則任何線程就沒法訪問了
try{
for(int i=0;i<length;i++){
System.out.print(string.charAt(i));
}
System.out.println();
}finally{
lock.unlock();
}
}
}
轉載于:https://www.cnblogs.com/huidaoli/articles/3602834.html
總結
- 上一篇: 001:简介
- 下一篇: srm#397_div1_500pt