首页 > 解决方案 > 同步方法同时执行

问题描述

根据 synchronized 关键字,如果应用于方法,则它会获取对象锁,并且具有相同实例的多个方法将无法同时执行这些方法。

但在下面的示例中,执行是同时发生的。请看一看:-

public class ncuie extends Thread{

    int b;
    ncuie(int a){
        b=a;
    }
    
    public synchronized void abc() throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            System.out.println("thread 1 "+i);
        }
    }
    
    public synchronized void pqr() throws InterruptedException {

        for (int i = 0; i < 10; i++) {
            System.out.println("thread 2 "+i);
        }
        
    }
    
    public void run() {
        
        try {
            if(b==5) {
            abc();
            }
            if(b==10) {
            pqr();
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
    
    public static void main(String[] args) {
        Thread t=new ncuie(5);
        Thread t1=new ncuie(10);
        t.start();
        t1.start();
    }
}

根据输出,有时执行线程 1,有时执行线程 2。理想情况下,只有一个线程应该获得锁并完成它的执行,然后才应该启动第二个线程。

输出:-

thread 1 0
thread 1 1
thread 2 0
thread 2 1
thread 2 2
thread 1 2
thread 1 3
thread 1 4
thread 1 5
thread 1 6
thread 1 7
thread 1 8
thread 2 3
thread 2 4
thread 2 5
thread 2 6
thread 1 9
thread 2 7
thread 2 8
thread 2 9

标签: javamultithreadingthread-safetysynchronizedjava.util.concurrent

解决方案


如果某些方法以这样的方式更改内部状态,以至于在同一实例上运行的其他方法会遇到麻烦,您通常会在您的实例上进行同步。在当前实例上同步 ( ) 是您通过在非静态方法上使用关键字或编写.thissynchronizedsynchronized(this) {...}

如果您的方法以这样的方式更改状态,即使在类的不同实例上操作的方法也会受到影响,您可以在类对象上进行同步。你通过写作来做到这一点synchronized(MyClass.class) {...}

如果你有静态方法需要与同一个类的其他静态方法同步,你可以通过synchronized在静态方法上使用关键字来获得类对象上的同步。

请注意,实例级同步和类级同步是完全独立的,这意味着,当类同步方法运行时,实例同步方法不会被阻塞。

在您的情况下,您在实例上同步,并且您有两个不同的实例,因此它们不会相互阻塞。


推荐阅读