在Java多线程中,可以使用synchronized关键字来实现线程之间的同步互斥,但在JDK1.5中新增加ReentranLock类也可以达到同样的效果,并且在扩展功能上更加强大,比如具有嗅探锁定、多路分支通知等,而且在使用上也比synchronized更加灵活。
代码测试片段一:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Demo002 {
public static void main(String[] args) {
Thread t1 = new DemoThread002();
Thread t2 = new DemoThread002();
t1.start();
t2.start();
}
}
class DemoThread002 extends Thread{
@Override
public void run() {
for (int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()+","+(i+1));
}
}
}
输出结果如下,没有顺序:
Thread-1,1
Thread-0,1
Thread-1,2
Thread-0,2
Thread-0,3
Thread-1,3
Thread-1,4
Thread-0,4
Thread-1,5
Thread-0,5
代码测试片段二:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Demo001 {
public static void main(String[] args) {
Lock lock = new ReentrantLock();
Thread t1 = new DemoThread001(lock);
Thread t2 = new DemoThread001(lock);
t1.start();
t2.start();
}
}
class DemoThread001 extends Thread{
private Lock lock;
public DemoThread001(Lock lock){
this.lock = lock;
}
@Override
public void run() {
lock.lock();
for (int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()+","+(i+1));
}
lock.unlock();
}
}
输出结果如下,有顺序:
Thread-0,1
Thread-0,2
Thread-0,3
Thread-0,4
Thread-0,5
Thread-1,1
Thread-1,2
Thread-1,3
Thread-1,4
Thread-1,5
代码测试片段三:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Demo001 {
public static void main(String[] args) {
Lock lock = new ReentrantLock();
Thread t1 = new DemoThread001(lock);
Thread t2 = new DemoThread001(lock);
Thread t3= new DemoThread001(lock);
t1.start();
t2.start();
t3.start();
}
}
class DemoThread001 extends Thread{
private Lock lock;
public DemoThread001(Lock lock){
this.lock = lock;
}
@Override
public void run() {
lock.lock();
for (int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()+","+(i+1));
}
lock.unlock();
}
}
输出结果如下:
Thread-0,1
Thread-0,2
Thread-0,3
Thread-0,4
Thread-0,5
Thread-2,1
Thread-2,2
Thread-2,3
Thread-2,4
Thread-2,5
Thread-1,1
Thread-1,2
Thread-1,3
Thread-1,4
Thread-1,5
重要结论:从运行结果来看,当前线程打印完毕之后将会对锁进行释放,其它线程才可以继续 打印。线程打印的数组是分级打印,因为当前线程已经持有锁,但线程之间打印的顺序是随机的。