当前位置 : 主页 > 编程语言 > c++ >

java多线程--死锁案例

来源:互联网 收集:自由互联 发布时间:2021-07-03
thread6占用thread7需要的资源,thread7占用thread6需要的资源,最终导致死锁 package cn.mym.thread;public class TestExclusionThread {static Object obj1 = new Object();static Object obj2 = new Object();public static void ma
thread6占用thread7需要的资源,thread7占用thread6需要的资源,最终导致死锁
package cn.mym.thread;



public class TestExclusionThread {
	
	static Object obj1  = new Object();
	static Object obj2  = new Object();
	public static void main(String[] args) {
		Thread6 t1 = new Thread6();
		Thread7 t2 = new Thread7();
		
		t1.start();
		t2.start();
		
		//System.out.println("ashfkdhsf");
	}
	
	
	static class Thread6 extends Thread{
		
	

		@Override
		public void run() {
			synchronized(obj1){
				System.out.println("obj1锁住了");
				
				synchronized(obj2){
					//锁住obj2
				}
				
			}
			
			
		}
		
	}
	static class Thread7 extends Thread{
		
		@Override
		public void run() {
			synchronized(obj2){
				System.out.println("obj2锁住了");
				
				synchronized(obj1){
					//锁住obj1
				}
				
			}
			
			
		}
		
	}
	
}
网友评论