多线程的东西看了有两三遍了,但是直到数据库这门专业课都学完了,印象还是不很深刻,在备考的时候死记硬背了一些事务啦、死锁啦、隔离级别之类的概念,跟多线程有点共通之处.
最近在看马士兵的视频教程,加深理解.
貌似java的多线程没有判断死锁的机制,数据库里面是会判断是否发生死锁的.下面这个例子里却是无止境地等待对方释放资源.
最近在看马士兵的视频教程,加深理解.
貌似java的多线程没有判断死锁的机制,数据库里面是会判断是否发生死锁的.下面这个例子里却是无止境地等待对方释放资源.
public class TestDeadLock implements Runnable {
public int flag = 1;
static Object o1 = new Object();
static Object o2 = new Object();
public static void main(String[] args) {
TestDeadLock t1 = new TestDeadLock();
TestDeadLock t2 = new TestDeadLock();
t1.flag = 0;
t2.flag = 1;
Thread th1 = new Thread(t1);
Thread th2 = new Thread(t2);
th1.start();
th2.start();
}
public void run() {
System.out.println("flag:"+flag);
if (flag == 1) {
synchronized (o1) {
try {
Thread.sleep(500);
} catch (Exception e) {
}
synchronized (o2) {
System.out.println("th1");
}
}
}
if (flag == 0) {
synchronized (o2) {
try {
Thread.sleep(500);
} catch (Exception e) {
}
synchronized (o1) {
System.out.println("th2");
}
}
}
}
}