public class testThread {
public static void main(String[] args) {
myThread mt = new myThread();
myThread mt1 = new myThread();
mt.flag = 1;
mt1.flag = 2;
Thread t = new Thread(mt);
Thread t1 = new Thread(mt1);
t.start();
t1.start();
}
}
class myThread implements Runnable{
int flag = 0; //设置一个标志
static String o1 = "STR!@!!!";
static String o2 = "STR2222";
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o2){
System.out.println(o2);
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}synchronized (o1) {
System.out.println(o1);
}
}
}
}
}
public static void main(String[] args) {
myThread mt = new myThread();
myThread mt1 = new myThread();
mt.flag = 1;
mt1.flag = 2;
Thread t = new Thread(mt);
Thread t1 = new Thread(mt1);
t.start();
t1.start();
}
}
class myThread implements Runnable{
int flag = 0; //设置一个标志
static String o1 = "STR!@!!!";
static String o2 = "STR2222";
public void run(){
System.out.println("******");
if(flag==1){ //标志为1,执行这里,先锁o1,然后再锁住o2,那么就将完成整个程序,o2被锁,相互等待
synchronized (o1) {try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o2){
System.out.println(o2);
}
}
}
synchronized (o2) { //先锁住对象2,休眠,然后再锁住o1,那么这里就可以执行完成,输出o1的值,但是因为o1整个被上一个if锁住,无法执行到o1
try {
Thread.sleep(0);} catch (InterruptedException e) {
e.printStackTrace();
}synchronized (o1) {
System.out.println(o1);
}
}
}
}
}