線程死鎖問題

線程死鎖就是線程之前相互爭奪對放所擁有的資源,並且不釋放資源,這樣下去就會造成死鎖。(個人見解)

package cn.sp.test02;
/**
 * 
 * @author 2YSP
 *線程死鎖問題
 */
public class TestDeadLock {
	//是指不同的線程分別佔用對方需要的同步資源不放棄,都再等待對方放棄自己需要的同步資源,就形成了線程的死鎖
	static StringBuffer sb1=new StringBuffer();
	static StringBuffer sb2=new StringBuffer();
	public static void main(String[] args) {
		new Thread(){
			public void run(){
				synchronized (sb1) {
					try {
						Thread.currentThread().sleep(10);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					sb1.append("A");
					synchronized (sb2) {
						sb2.append("B");
						System.out.println(sb1);
						System.out.println(sb2);
					}
				}
				
			}
		}.start();
		new Thread(){
			public void run(){
				synchronized (sb2) {
					sb1.append("C");
					synchronized (sb1) {
						sb2.append("D");
						System.out.println(sb1);
						System.out.println(sb2);
					}
				}
			}
		}.start();
	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章