Skip to content

Commit

Permalink
公平锁与非公平锁
Browse files Browse the repository at this point in the history
  • Loading branch information
xuchang1 committed Jul 9, 2019
1 parent 9407118 commit f1ab395
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 1 deletion.
26 changes: 26 additions & 0 deletions src/main/java/thread_demo/demo43/MyService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package thread_demo.demo43;

import java.util.concurrent.locks.ReentrantLock;

public class MyService {

private ReentrantLock lock;

public MyService(boolean isFair) {
this.lock = new ReentrantLock(isFair);
}

public void method1() {
System.out.println("thread name : " + Thread.currentThread().getName() + " 尝试获取锁, at " + System.currentTimeMillis());
lock.lock();
System.out.println("thread name : " + Thread.currentThread().getName() + " 获取到了锁");
lock.unlock();
}

public void method2() throws InterruptedException {
lock.lock();
Thread.sleep(5000);
System.out.println("method2 释放锁");
lock.unlock();
}
}
15 changes: 15 additions & 0 deletions src/main/java/thread_demo/demo43/MyThread.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package thread_demo.demo43;

public class MyThread extends Thread {

private MyService service;

public MyThread(MyService service) {
this.service = service;
}

@Override
public void run() {
service.method1();
}
}
43 changes: 43 additions & 0 deletions src/main/java/thread_demo/demo43/Run.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package thread_demo.demo43;

/**
*公平锁与非公平锁 :
* 公平锁 : 线程获取锁的顺序是按照线程加载锁的顺序来的(FIFO的顺序)
* 非公平锁 : 线程获取锁的顺序是随机的,和线程加载锁的顺序没有关系
*
* new ReentrantLock(true) : 公平锁; new ReentrantLock(false) : 非公平锁
*/
public class Run {

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

final MyService service = new MyService(true);
//TODO
//好像都是公平锁,为什么没有效果?
// final MyService service = new MyService(false);

Thread[] threads = new Thread[40];
for (int i = 0; i < threads.length; i++) {
threads[i] = new MyThread(service);
}

new Thread() {
@Override
public void run() {
try {
service.method2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();

Thread.sleep(100);

for (int i = 0; i < threads.length; i++) {
threads[i].start();
Thread.sleep(100);
}
}

}
4 changes: 3 additions & 1 deletion src/main/java/thread_demo/description.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,6 @@ demo40 : InheritableThreadLocal使用。

demo41 : ReentrantLock使用。

demo42 : Condition调用await、signal方法进行等待、唤醒。
demo42 : Condition调用await、signal方法进行等待、唤醒。

demo43 : new ReentrantLock(true) : 公平锁;new ReentrantLock(false) : 非公平锁。

0 comments on commit f1ab395

Please sign in to comment.