public class BankDemo {
public static void main(String[] args) {
Cus c = new Cus();
new Thread(c).start();
new Thread(c).start();
}
}
同步中嵌套同步,用到不同的锁。
public class Test implements Runnable {
private boolean flag;
Test(boolean flag) {
this.flag = flag;
}
public void run() {
if (flag) {
while (true) {
synchronized (MyLock.locka) {
System.out.println(Thread.currentThread().getName() + "...if locka ");
synchronized (MyLock.lockb) {
System.out.println(Thread.currentThread().getName() + "..if lockb");
}
}
}
} else {
while (true) {
synchronized (MyLock.lockb) {
System.out.println(Thread.currentThread().getName() + "..else lockb");
synchronized (MyLock.locka) {
System.out.println(Thread.currentThread().getName() + ".....else locka");
}
}
}
}
}
}
class MyLock {
static Object locka = new Object();
static Object lockb = new Object();
}class DeadLockTest {
public static void main(String[] args) {
/* Thread t1 = new Thread(new Test(true));
Thread t2 = new Thread(new Test(false));
t1.start();
t2.start(); */
new Thread(new Test(true)).start();//匿名对象,对上面简化
new Thread(new Test(false)).start();
}
}
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-55883-4.html
日子没法过了
“天下没有人靠炒股发财”说的绝对了
从这次行动来看
没人希望战争