java面试题—-用java代码写死锁
线程join写法
public class Test2 {
//join写线程死锁
//join 等待该线程终止,即把对象所在当前的线程停止
public static void main(String[] args) {
// TODO Auto-generated method stub
//创建线程myth1并赋相应的值
MyThread myth1=new MyThread();
myth1.paraC='5';
myth1.star='0';
myth1.random=10;
//创建线程myth2并赋相应的值
MyThread myth2=new MyThread();
myth2.paraC='f';
myth2.star='a';
myth2.random=26;
//myth2的线程引用指向线程myth1,myth1的线程引用指向线程myth2
//为死锁创建条件
myth1.t=myth2;
myth2.t=myth1;
myth1.start();
myth2.start();
}
}
//MyThread类继承Thread并实现run方法
class MyThread extends Thread{
char paraC,star;
int random;
Thread t;
public void run(){
for (int i = 0; i < 200; i++) {
char c=(char)((int)(Math.random()*random)+star);
System.out.println(c);
if(c==paraC){
try {
//这里注意不要用this,this并不代表本线程,代表虚拟机
//start方法为使该线程开始执行;Java 虚拟机调用该线程的 run 方法
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}