java中Synchronized引起的并發(fā)線程的無限等待的解決方法
Synchronized引起的并發(fā)線程的無限等待的解決方法
我們在數(shù)據(jù)庫并發(fā)訪問中經(jīng)常用到:select * from table for update,這句話會引起所有執(zhí)行這句話的線程排隊(duì),一個一個的序列執(zhí)行。等待的線程只能死等,直到超時為止。下面程序的f1就模仿這句話的感覺。
例1.9.6:
class A {
public synchronized void f1() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("f1模仿select * from table for update,執(zhí)行的很慢"+Thread.currentThread().getName());
}
}
class MyThread1 extends Thread {
A a;
public MyThread1(A a) {
this.a = a;
}
public void run() {
a.f1();
}
}
public class TestMark_to_win {
public static void main(String[] args) {
MyThread1[] threads = new MyThread1[3];
A a = new A();
for (int i = 0; i < 3; i++) {
threads[i] = new MyThread1(a);
threads[i].start();
}
}
}
輸出結(jié)果:
f1模仿select * from table for update,執(zhí)行的很慢Thread-0
f1模仿select * from table for update,執(zhí)行的很慢Thread-2
f1模仿select * from table for update,執(zhí)行的很慢Thread-1
下面程序的concuNum會記錄,現(xiàn)在隊(duì)列里多少人在排隊(duì)。selectForUpdateIntel就成了智能版的select * from table for update,人少我就排隊(duì),人多我就直接撤。
例1.9.6:
class A {
int concuNum=0;
private synchronized void selectForUpdateSyn() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("模仿select * from table for update,執(zhí)行的很慢"
+ Thread.currentThread().getName()+"目前隊(duì)中有"+concuNum+"人");
}
public void selectForUpdate() {
concuNum++;
selectForUpdateSyn();
concuNum--;
}
public void selectForUpdateIntel() {
if(concuNum<3){
System.out.println("我是聰明人,目前隊(duì)中人不多,有"+concuNum+"人,我等");
selectForUpdate();
}else {
System.out.println(concuNum+"! 我是聰明人,排隊(duì)人太多,我先不排了");
}
}
}
class MyThread1 extends Thread {
A a;
public MyThread1(A a) {
this.a = a;
}
public void run() {
a.selectForUpdate();
}
}
class MyThread2 extends Thread {
A a;
public MyThread2(A a) {
this.a = a;
}
public void run() {
a.selectForUpdateIntel();
}
}
public class TestMark_to_win {
public static void main(String[] args) {
MyThread1[] threads = new MyThread1[3];
A a = new A();
for (int i = 0; i < 3; i++) {
threads[i] = new MyThread1(a);
}
MyThread2 myThread2=new MyThread2(a);
threads[0].start();
threads[1].start();
myThread2.start();
threads[2].start();
}
}
運(yùn)行結(jié)果:
3! 我是聰明人,排隊(duì)人太多,我先不排了
模仿select * from table for update,執(zhí)行的很慢Thread-0目前隊(duì)中有3人
模仿select * from table for update,執(zhí)行的很慢Thread-1目前隊(duì)中有2人
模仿select * from table for update,執(zhí)行的很慢Thread-2目前隊(duì)中有1人
運(yùn)行結(jié)果有時又變成:
我是聰明人,目前隊(duì)中人不多,有1人,我等
模仿select * from table for update,執(zhí)行的很慢Thread-1目前隊(duì)中有4人
模仿select * from table for update,執(zhí)行的很慢Thread-2目前隊(duì)中有3人
模仿select * from table for update,執(zhí)行的很慢Thread-0目前隊(duì)中有2人
模仿select * from table for update,執(zhí)行的很慢Thread-3目前隊(duì)中有1人