Semaphore替换多线程synchronized解决并发环境死锁,Java
Posted zhangphil
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Semaphore替换多线程synchronized解决并发环境死锁,Java相关的知识,希望对你有一定的参考价值。
Semaphore替换多线程synchronized解决并发环境死锁,Java
import java.util.concurrent.Semaphore;
public class MainClass
private Semaphore semaphore1 = new Semaphore(1);
private Semaphore semaphore2 = new Semaphore(1);
public static void main(String[] args)
MainClass mainClass = new MainClass();
mainClass.demo();
private void demo()
Thread ta = new Thread(new DeadA());
Thread tb = new Thread(new DeadB());
ta.start();
tb.start();
private class DeadA implements Runnable
private String id = "A";
@Override
public void run()
System.out.println(id + " 申请锁1...");
try
semaphore1.acquire();
catch (InterruptedException e)
throw new RuntimeException(e);
System.out.println(id + " 获得锁1");
semaphore1.release();
System.out.println(id + " 申请锁2...");
try
semaphore2.acquire();
catch (InterruptedException e)
throw new RuntimeException(e);
System.out.println(id + "获得锁2");
semaphore2.release();
System.out.println(id + " 运行结束");
private class DeadB implements Runnable
private String id = "B";
@Override
public void run()
System.out.println(id + " 申请锁2...");
try
semaphore2.acquire();
catch (InterruptedException e)
throw new RuntimeException(e);
System.out.println(id + " 获得锁2");
semaphore2.release();
System.out.println(id + " 申请锁1...");
try
semaphore1.acquire();
catch (InterruptedException e)
throw new RuntimeException(e);
System.out.println(id + " 获得锁1");
semaphore1.release();
System.out.println(id + " 运行结束");
输出:
A 申请锁1...
B 申请锁2...
A 获得锁1
B 获得锁2
A 申请锁2...
B 申请锁1...
A获得锁2
B 获得锁1
A 运行结束
B 运行结束
以上是关于Semaphore替换多线程synchronized解决并发环境死锁,Java的主要内容,如果未能解决你的问题,请参考以下文章
ReentrantLock替换synchronized解决多线程并发死锁,Java