java多執行緒上機題,寫一個簡單的死鎖程式
阿新 • • 發佈:2019-02-05
下面是一個非常簡單的會出現死鎖的程式:
*/package com.richinfo.cn.thread;
/**
* @author : Allen(Wu Zhiwei)
* @date 建立時間:2018年5月17日 下午8:58:20
* @version 1.0
* @parameter
* @since
* @return
*/
/**
* @author Allen
*
*/
public class DeathLockTest implements Runnable{
private String s1 = new String();
private String s2 = new String();
public void fun1(){
synchronized(s1){
try {
System.out.println(Thread.currentThread().getName() + "執行fun1");
s1.wait(1000);
System.out.println(Thread.currentThread().getName() + "執行fun1等待之後");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fun2();
}
}
public void fun2(){
synchronized(s2){
try {
System.out.println(Thread.currentThread().getName() + "執行fun2" );
s2.wait(1000);
System.out.println(Thread.currentThread().getName() + "執行fun2等待之後");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fun1();
}
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
this.fun1();
}
/**
* @param args
*/
public static void main(String[] args) {
DeathLockTest dt = new DeathLockTest();
Thread t1 = new Thread(dt);
t1.start();
Thread t2 = new Thread(dt);
t2.start();
System.out.println("主執行緒執行完成");
}
}