首页 > 解决方案 > 在同一个类中执行同步和非同步方法

问题描述

我在一个类中有两种方法,一种是同步的,另一种是非同步的。当我用两个不同的线程调用这些方法时,我看到执行变为串行而不是并行。

我很困惑,根据理论r.processSomething()不应该等待r.doSomething()完成其执行。

如果有人对同时执行两种方法(同步和非同步)有一些想法。请分享。

class LockObjectDemo{

    public static void main(String[] args){

        SharedResource r = new SharedResource();

        MyThread t1 = new MyThread(r);
        t1.start();

        MyThread t2 = new MyThread(r);
        t2.start();

    }
}


class MyThread extends Thread{
    private SharedResource r ;

    MyThread(SharedResource r){
        this.r = r;
    }

    public void run() {     
        try {
            r.doSomething(); // Only after completing this method , the other thread enters into the next method which is not locked
            r.processSomething();           
        } catch(Exception ex){
            System.out.println(ex);
        }

    }
}

class SharedResource{

    public void doSomething() throws Exception{
        synchronized(this){ 
            System.out.println("Doing Something -> "+Thread.currentThread().getName());
            Thread.sleep(5000);
            System.out.println("Done Something->"+Thread.currentThread().getName());
        }
    }

    public void processSomething() throws Exception{
        System.out.println("Processing Something -> "+Thread.currentThread().getName());
        Thread.sleep(1000);
        System.out.println("Done Processing->"+Thread.currentThread().getName());
    }
}

标签: javamultithreadingsynchronizationlockingdeadlock

解决方案


你有两件事,大约 5 秒,连续执行(因为synchronized)。

当第一个线程完成 5s 动作时,它开始花费约 1s 的时间,同时,第二个线程开始 5s 动作。

第一个线程将在第二个线程完成 5s 动作之前完成 1s 动作。然后第二个线程执行 1s 动作。

因此,1s 动作不会同时执行。

图形化:

Thread 1:  |<----- 5s ----->|<- 1s ->|
Thread 2:                   |<----- 5s ----->|<- 1s ->|

推荐阅读