java中Synchronized引起的并发线程的无限等待的解决方法

Synchronized引起的并发线程的无限等待的解决方法  

我们在数据库并发访问中经常用到:select * from table for update,这句话会引起所有执行这句话的线程排队,一个一个的序列执行。等待的线程只能死等,直到超时为止。下面程序的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,执行的很慢"+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();
        }
    }
}

更多内容请见原文,文章转载自:https://blog.csdn.net/qq_43650923/article/details/101195799

posted @ 2021-04-30 09:30  小龙虾1  阅读(554)  评论(0)    收藏  举报