Java并发编程五公平锁和重入锁ReentrantLock与synchronized

编程

1.重入锁ReentrantLock与synchronized的区别

synchronized 与重入锁是一样的,新旧线程一直可以一起竞争锁。

1.synchronized属于java关键字,

2.synchronized能对方法,代码块,对象进行加锁。

3.ReentrantLock需要执行lock()上锁unlock()解锁。

public class Test {

//true 为公平锁,false为重入锁

public static ReentrantLock lock = new ReentrantLock(false);

public static void main(String [] args) throws InterruptedException {

ThreadJoinTest t1 = new ThreadJoinTest("李雷");

ThreadJoinTest t2 = new ThreadJoinTest("韩梅梅");

ThreadJoinTest t3 = new ThreadJoinTest("露西");

ThreadJoinTest t4 = new ThreadJoinTest("莉莉");

t1.start();

t2.start();

t3.start();

t4.start();

System.out.println("Main thread is finished");

}

}

class ThreadJoinTest extends Thread{

public ThreadJoinTest(String name){

super(name);

}

@Override

public void run(){

Test.lock.lock();

for(int i=0;i<3;i++){

System.out.println(this.getName() + ":" + DateUtil.formatTime(new Date()));

ThreadUtil.sleep(1000);

}

Test.lock.unlock();

}

}

执行结果  线程随机执行

Main thread is finished
露西:15:12:28
露西:15:12:29
露西:15:12:30
莉莉:15:12:31
莉莉:15:12:32
莉莉:15:12:33
韩梅梅:15:12:34
韩梅梅:15:12:35
韩梅梅:15:12:36
李雷:15:12:37
李雷:15:12:38
李雷:15:12:39

synchronized 的结果是一样的

2.公平锁

公平锁可以理解为线程池的newSingleThreadExecutor,锁先到先得

public class Test {

//true 为公平锁,false为重入锁

public static ReentrantLock lock = new ReentrantLock(true);

public static void main(String [] args) throws InterruptedException {

ThreadJoinTest t1 = new ThreadJoinTest("李雷");

ThreadJoinTest t2 = new ThreadJoinTest("韩梅梅");

ThreadJoinTest t3 = new ThreadJoinTest("露西");

ThreadJoinTest t4 = new ThreadJoinTest("莉莉");

t1.start();

t2.start();

t3.start();

t4.start();

System.out.println("Main thread is finished");

}

}

class ThreadJoinTest extends Thread{

public ThreadJoinTest(String name){

super(name);

}

@Override

public void run(){

Test.lock.lock();

for(int i=0;i<3;i++){

System.out.println(this.getName() + ":" + DateUtil.formatTime(new Date()));

ThreadUtil.sleep(1000);

}

Test.lock.unlock();

}

}

执行结果  按线程start的顺序

Main thread is finished
李雷:15:33:54
李雷:15:33:55
李雷:15:33:56
韩梅梅:15:33:57
韩梅梅:15:33:58
韩梅梅:15:33:59
露西:15:34:00
露西:15:34:01
露西:15:34:02
莉莉:15:34:03
莉莉:15:34:04
莉莉:15:34:05

 

 

 

以上是 Java并发编程五公平锁和重入锁ReentrantLock与synchronized 的全部内容, 来源链接: utcz.com/z/515545.html

回到顶部