线程死锁:在实现多线程时,不要出现锁嵌套的行为,否则会出现线程相互等待的死锁情况。比如以下代码
package work5;
public class text {
/**
* @param args
*/
public static Object lock=new Object();
public static Object lock2=new Object();
public static void main(String[] args) {
Thea thea=new Thea(true);
Thea thea2=new Thea(false);
thea.start();
thea2.start();
}
}
package work5;
public class Thea extends Thread {
private boolean f;
private Thea(){}
public Thea(boolean f){
this.f=f;
}
@Override
public void run() {
while(true){
if(f){
synchronized (text.lock) {
System.out.println(1);
synchronized (text.lock2) {
System.out.println(2);
}
}
}else{
synchronized (text.lock2) {
System.out.println(3);
synchronized (text.lock) {
System.out.println(4);
}
}
}
}
}
}
|