java中类中多个Synchronized方法

类中多个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);

版权保护原文出处:http://www.mark-to-win.com/index.html?content=JavaBeginner/javaUrl.html&chapter=JavaBeginner/JavaBeginner6_web.html#MultiSynchronized

猜你喜欢

转载自blog.csdn.net/mark_to_win/article/details/89284898
今日推荐