1 具有线程锁的安全机制
2 可以在各个线程抢占时,线程之间切换更加频繁
代码如下
package com.exception2;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
class Ex4 implements Runnable {
private int taks=100;
private ReentrantLock lk=new ReentrantLock(true);
@Override
public void run() {
while (true){
try{
lk.lock();
if(taks>0){
try {
Thread.sleep(40);
}catch (Exception e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":"+taks--);
}else {
break;
}
}finally {
lk.unlock();
}
}
}
}
public class Main4 {
public static void main(String[] args) {
Ex4 e=new Ex4();
new Thread(e).start();
new Thread(e).start();
new Thread(e).start();
new Thread(e).start();
new Thread(e).start();
new Thread(e).start();
new Thread(e).start();
new Thread(e).start();
new Thread(e).start();
new Thread(e).start();
new Thread(e).start();
new Thread(e).start();
}
}
private ReentrantLock lk=new ReentrantLock(true);
锁机制为true时 运行效果
private ReentrantLock lk=new ReentrantLock(false);//不写参数时候,默认也为false
锁机制为false时 运行效果