java 死锁

来源:互联网 发布:搜狐 网络大电影 编辑:程序博客网 时间:2024/06/16 06:32

死锁由多线程带来的性能改善是以可靠性为代价的,主要是因为有可能产生线程死锁。死锁是这样一种情形:多个线程同时被阻塞,它们中的一个或者全部都在等待某个资源被释放。由于线程被无限期地阻塞,因此程序不能正常运行。简单的说就是:线程死锁时,第一个线程等待第二个线程释放资源,而同时第二个线程又在等待第一个线程释放资源。

示例代码:

package main;public class Main {// 死锁案例public static void main(String[] args) {Thread t1 = new Thread(new StudentA());Thread t2 = new Thread(new StudentB());t1.start();t2.start();}static Object N = new Object();// N锁static Object P = new Object();// P锁static class StudentA implements Runnable {@Overridepublic void run() {synchronized (N) {System.out.println(Thread.currentThread().getName() + "获得N锁");try {Thread.sleep(1000);// 睡眠一秒 ,保证两个线程同步执行(并发),否则线程启动有差异影响测试结果} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName() + "想要获得P锁,才释放N锁");synchronized (P) {System.out.println(Thread.currentThread().getName() + "获得P锁");}System.out.println(Thread.currentThread().getName() + "释放P锁");}System.out.println(Thread.currentThread().getName() + "释放N锁");}}static class StudentB implements Runnable {@Overridepublic void run() {synchronized (P) {System.out.println(Thread.currentThread().getName() + "获得P锁");try {Thread.sleep(1000);// 睡眠一秒 ,保证两个线程同步执行(并发)} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName() + "想要获得N锁,才释放P锁");synchronized (N) {System.out.println(Thread.currentThread().getName() + "获得N锁");}System.out.println(Thread.currentThread().getName() + "释放N锁");}System.out.println(Thread.currentThread().getName() + "释放P锁");}}}


截图:


原创粉丝点击