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时 运行效果

本文深入探讨了线程锁机制在并发控制中的作用,通过ReentrantLock类的使用实例,展示了如何在线程间实现安全的数据操作。代码示例中,通过设置不同的公平锁策略,观察并比较了线程调度的效果。
526





