java - 在同一个类中执行同步和非同步方法

标签 java multithreading synchronization locking deadlock

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

我很困惑,根据理论 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());
    }
}

最佳答案

你有两件事,需要大约 5 秒,串行执行(因为同步)。

当第一个线程完成 5 秒的操作时,它会开始大约 1 秒的时间,同时,第二个线程开始 5 秒的操作。

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

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

图形化:

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

关于java - 在同一个类中执行同步和非同步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55728123/

相关文章:

postgresql - 插入后同步两个表

c - MPI_Bcasts 卡在奴隶上

java - Java 列问题中的 GridBagLayout

java - 如何使用strut标签比较0和1

c# - 任务延迟与线程休眠解析精度

c# - 数小时后 RAM 密集型 C# 进程变慢

java - HttpSession 和 JBoss。 session 超时有什么影响?

java - 如何删除 Netbean 6.8 中的生成源(jax-ws)?我应该根据网站地址从 WSDL 生成 WS 客户端还是从 api 生成 WS 客户端?

c# - sleep /等待很长时间

linux - 在 Linux 中用 C 语言阻止 alarm()