java - 在同一个类中执行同步和非同步方法
问题描述
我在一个类中有两种方法,一种是同步的,另一种是非同步的。当我用两个不同的线程调用这些方法时,我看到执行变为串行而不是并行。
我很困惑,根据理论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 秒,连续执行(因为synchronized
)。
当第一个线程完成 5s 动作时,它开始花费约 1s 的时间,同时,第二个线程开始 5s 动作。
第一个线程将在第二个线程完成 5s 动作之前完成 1s 动作。然后第二个线程执行 1s 动作。
因此,1s 动作不会同时执行。
图形化:
Thread 1: |<----- 5s ----->|<- 1s ->|
Thread 2: |<----- 5s ----->|<- 1s ->|
推荐阅读
- python - ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all() 进行图像处理
- c++ - 在 C++ 中从 double 转换为 int
- php - 如何通过 .htaccess 重写 url
- html - 动画 CSS Uncentering Div
- javascript - 发表的评论仅在刷新时呈现在 DOM 中(React)
- javascript - 使用 HTML 和 JS 通过 URL 访问 XML 文件
- java - Kotlin Gradle API 依赖项在消费者中不可用
- apache-flink - Flink 的 hive 流与 iceberg/hudi/delta
- android-studio - Flutter Advance pdf 查看器插件在模拟器中运行良好,但在真实设备中显示错误
- android - 为什么在颤动中热加载后旧视图仍在屏幕上