2017-08-03(多线程死锁&匿名内部类)
public class deadlock implements Runnable {
public int flag ;
private static Object OB1 = new Object(), OB2 = new Object(); // 静态对象是类的所有对象共享的
@Override
public void run() {
System.out.println("flag=" + flag);
if (flag == 1) {
synchronized (OB1) {
try {
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (OB2) {
System.out.println("1");
}
}
}
else {
synchronized (OB2) {
try {
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (OB1) {
System.out.println("0");
}
}
}
}
public static void main(String[] args) {
deadlock td1 = new deadlock();
deadlock td2 = new deadlock();
td1.flag = 1;
td2.flag = 0;
new Thread(td1).start(); //td1,td2都处于可执行状态,但JVM线程调度先执行哪个线程是不确定的。
new Thread(td2).start(); //td2的run()可能在td1的run()之前运行
}
}
--------------------------------------------------多线程匿名内部类---------------------------------------------------------------------
public class nbl extends Thread{
public static void main(String[] args) {
new Thread() {
public void run() {
for (int x = 0; x < 100; x++) {
System.out.println(Thread.currentThread().getName() + "--"
+ x);
}
}
}.start();
}
}