首页 > 编程语言 > 详细

java中类中多个Synchronized方法

时间:2021-04-30 09:53:02      阅读:16      评论:0      收藏:0      [点我收藏+]

类中多个Synchronized方法  

下面给出一个例子,说明一个class中有两个方法synchronized的情况。它们互相阻挡的用法和上面的“一个方法有synchronized”的情况是一样的。
例1.9.5:
class A {
    public synchronized void f1() {
        for (int i = 0; i < 3; i++) {
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
            }
            System.out.println("f1 i = " + i);
        }
    }
    
    public synchronized void f2() {
        for (int i = 0; i < 3; i++) {
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
            }
            System.out.println("f2 i = " + i);
        }
    }
}

class MyThread1 extends Thread {
    A a;
    public MyThread1(A a) {
        this.a = a;
    }
    public void run() {
        a.f1();
    }
}

class MyThread2 extends Thread {
    A a;
    public MyThread2(A a) {
        this.a = a;
    }
    public void run() {
        a.f2();
    }
}
public class TestMark_to_win {
    public static void main(String[] args) {
        A a = new A();
        Thread t1 = new MyThread1(a);
        Thread t2 = new MyThread2(a);
        t1.start();
        t2.start();
    }
}

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

java中类中多个Synchronized方法

原文:https://www.cnblogs.com/xiaolongxia1922/p/14720684.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!