举个通俗易懂的例子,需要被同步访问的资源就好比是公共厕所:
1. CRITICAL_SECTION(临界区): 公厕管理人员每次允许一个人进入,直到他出去了,下一个人才可以进入。
2. Event(事件): 他告诉你公厕里面当前的状态。但是,你可以闯进去。他不会管你。要干什么取决于你。
3. Semaphore(信号量): 他允许公厕里面有N个人同时用,再多的人就必须排队。
4. mutex(互斥量): 厕所是属于他的。他用的时候,别人决不能进去。他不用的时候,得到他的允许,别人才能进去。他也可以选择让厕所空着。
java中的互斥量:
import java.util.concurrent.locks.ReentrantLock;
public class ReentranLockExample {
private static int count = 0;
private static ReentrantLock reentrantLock = new ReentrantLock();
static class MyThread extends Thread{
@Override
public void run() {
super.run();
try {
while (true){
boolean result = reentrantLock.tryLock();
if (result){
System.out.println(Thread.currentThread().getName() + "get the lock success and run the syn code " + count ++);
reentrantLock.unlock();
}else{
System.out.println(Thread.currentThread().getName() + "get the lock failed and run the syn code " + count);
}
System.out.println(Thread.currentThread().getName() + "run the asyntronized code " + count);
Thread.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args){
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start();
thread2.start();
}
}
java中的信号量
import java.util.concurrent.Semaphore;
public class SemaphoreExample {
private static Semaphore semaphore = new Semaphore(2);
private String lock = "lock";
private static volatile int count = 0;
static class MyThread extends Thread {
@Override
public void run() {
super.run();
try {
while (true) {
semaphore.acquire();
Thread.sleep(500);
System.out.println(Thread.currentThread().getName() + "get the lock success and run the syn code " + count++);
semaphore.release();
System.out.println(Thread.currentThread().getName() + "get the unlock success");
Thread.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args){
MyThread thread1 = new MyThread();
thread1.setName("thread_1");
MyThread thread2 = new MyThread();
thread2.setName("thread_2");
MyThread thread3 = new MyThread();
thread3.setName("thread_3");
thread1.start();
thread2.start();
thread3.start();
}
}
java中的临界区:
synchronized(Object.class){
//CRITICAL_SECTION
}