我在一个类中有两种方法,一种是同步的,另一种是非同步的。当我使用两个不同的线程调用这些方法时,我看到执行变成串行而不是并行。
我很困惑,根据理论 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/