synchronized有增强版。那!就!是! concurrent并发包。
首先说一下重入锁。
import java.util.concurrent.locks.ReentrantLock;
public class DemoThread extends Thread {
public static ReentrantLock reentrantLock = new ReentrantLock();
public static int time = 0;
public static void main(String[] args) throws InterruptedException {
DemoThread demoThread = new DemoThread();
demoThread.start();
DemoThread demoThread1 = new DemoThread();
demoThread1.start();
demoThread.join();
demoThread1.join();
System.out.println(time);
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
reentrantLock.lock();
time++;
System.out.println(Thread.currentThread().getName() + "__" + time);
reentrantLock.unlock();
}
}
}
使用重入锁,可保证在同一时刻只有一个线程访问锁区。和syn是同样的,它只保证锁区内部的对象一次只有一个线程取得,锁区外面可对对象进行操作。线程肯定不安全。
我看看,并发包锁应该是对某一点程序锁死,同一时间只能同一线程进行操作。其他线程对也能对锁区内部的任何对象进行操作。而且线程不安全。故线程之间通信的对象应该全部都锁区内进行。
锁同样可解决锁死的问题。
lockInterruptibly
大意是退出另一个线程。我觉得还不如wait()好用。
import java.util.concurrent.locks.ReentrantLock;
public class DemoThread extends Thread {
public static ReentrantLock reentrantLock = new ReentrantLock();
public static ReentrantLock reentrantLock1 = new ReentrantLock();
public static int time = 0;
public static void main(String[] args) throws InterruptedException {
DemoThread demoThread = new DemoThread();
demoThread.start();
DemoThread demoThread1 = new DemoThread();
demoThread1.start();
demoThread.join();
demoThread1.join();
System.out.println(time);
}
@Override
public void run() {
for (int i = 0; i < 100000; i++) {
reentrantLock.lock();
time++;
System.out.println(Thread.currentThread().getName() + "__" + time);
reentrantLock.lock();
time--;
reentrantLock.unlock();
reentrantLock.unlock();
System.out.println(reentrantLock.getHoldCount());
System.out.println(reentrantLock.getQueueLength());
System.out.println(reentrantLock.isLocked());
}
}
}
总的来说,并发包提供了一个对锁状态比较好的监控。
某一线程的程序执行到一段有锁的代码的时候,首先会到等待队列中,请求锁。等到有线程释放锁的时候,系统从等待队列中唤醒一个线程,继续工作。