java学习多线程之死锁
2013-10-20 16:09
429 查看
形成死锁的前提是同步代码块嵌套。
什么是死锁?当一个线程拿到锁以后在这个锁内部的代码需要访问另一段的代码的时候另外一个程序的锁被另外一个线程拿到,这样的话,就造成了两个锁互不想让程序没法往下执行的这种状况就是死锁。
以上就是一个死锁。
简单来说就是一段程序代码中有两个同步的代码块嵌套,也就是有两个锁,但是一个锁的执行依赖另外一个锁。
代码中A方法要调用B方法,同时这两个都是同步的,有各自的锁A比如说有A锁,B比如说有B锁,那么A方法要执行完成的话,必须同时具备A锁和B锁,如果此时B锁被其他线程拿到的话,这个时候A就等待B锁,同时其他线程也没法执行A方法,这个时候就是相互僵持,成为死锁。同时要注意,锁这个概念是针对线程的,跟本身的程序没有关系。我们再来写个死锁的示例:
什么是死锁?当一个线程拿到锁以后在这个锁内部的代码需要访问另一段的代码的时候另外一个程序的锁被另外一个线程拿到,这样的话,就造成了两个锁互不想让程序没法往下执行的这种状况就是死锁。
class DeadDemoA implements Runnable { Object obj = new Object(); int x = 0; public void run() { if(x == 0){ while(true) { synchronized(obj) { System.out.println("-----"); showA(); System.out.println("-----"); } showA(); } }else{ while(true) { showA(); x = x+1; x = x%2; } } } public synchronized void showA() { synchronized (obj) { System.out.println("SI suo"); } } } class DeadLock { public static void main(String[] args) { DeadDemoA a = new DeadDemoA(); Thread t1 = new Thread(a); Thread t2 = new Thread(a); Thread t3 = new Thread(a); Thread t4 = new Thread(a); t1.start(); t2.start(); t3.start(); t4.start(); } }
以上就是一个死锁。
简单来说就是一段程序代码中有两个同步的代码块嵌套,也就是有两个锁,但是一个锁的执行依赖另外一个锁。
代码中A方法要调用B方法,同时这两个都是同步的,有各自的锁A比如说有A锁,B比如说有B锁,那么A方法要执行完成的话,必须同时具备A锁和B锁,如果此时B锁被其他线程拿到的话,这个时候A就等待B锁,同时其他线程也没法执行A方法,这个时候就是相互僵持,成为死锁。同时要注意,锁这个概念是针对线程的,跟本身的程序没有关系。我们再来写个死锁的示例:
class DDlock1 implements Runnable { private Object obj = new Object(); public void run() { while(true) { synchronized (obj) { show(); } show();//let other thread get the lock } } public synchronized void show() { synchronized(obj){ System.out.println("Dead lock example~"); } } } class DeadLock1 { public static void main(String[] args) { DDlock1 d = new DDlock1(); Thread t1 = new Thread(d); Thread t2 = new Thread(d); Thread t3 = new Thread(d); Thread t4 = new Thread(d); t1.start(); t2.start(); t3.start(); t4.start(); } }
相关文章推荐
- java 多线程学习笔记2-同步代码块,死锁
- java学习日记(6)____多线程的安全问题与死锁的产生
- [原]Java多线程编程学习笔记之八:死锁(含代码)
- [原]Java多线程编程学习笔记之八:死锁(含代码)
- 学习笔记 java多线程 信号量(Semaphore),死锁
- Java学习提要——简述多线程的同步synchronized与死锁
- java学习第十二天之多线程死锁和并发
- Java学习疑点(5)--使用多线程的时候如何注意避免死锁发生?
- java基础知识回顾之java Thread类学习(七)--java多线程安全问题(死锁)
- java多线程学习之死锁的模拟和避免
- java学习--多线程发生死锁的一个例子
- Java多线程学习笔记3——ReentranLock和ReentrantReadWriteLock
- Java菜鸟学习笔记--多线程篇(三):线程死锁
- JAVA 多线程和并发学习笔记(二)
- 当年第一次学习java多线程写的例子,从此多线程不再陌生
- 多线程学习记录2-java5的一些线程池
- java 多线程学习笔记
- java学习笔记--多线程
- JAVA多线程与并发学习总结
- java多线程总结学习-Queue、容器、单例模式