线程安全问题(锁机制,同步技术)
2019-08-07 本文已影响0人
奇怪的双子座
package com.lqf;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SyncRunableImpl implements Runnable{
private int ticker=100;
Lock lock=new ReentrantLock();
//创建一个锁对象
Object obj=new Object();
// @Override
// public void run(){
// while (ticker>0){
// synchronized (obj){
// try {
// Thread.sleep(1000);
// }catch (InterruptedException e){
// e.getMessage();
// }
// System.out.println(ticker+"ticker");
// ticker--;
// }
//
// }
//
// }
@Override
public void run(){
while (ticker>0){
lock.lock();
try {
Thread.sleep(1000);
System.out.println(ticker+"ticker");
ticker--;
}catch (InterruptedException e){
e.getMessage();
}finally {
lock.unlock();
}
}
}
}