feat: synchronized-1
This commit is contained in:
parent
c334d09d65
commit
8a8881fd03
|
@ -0,0 +1,14 @@
|
|||
package thead.thread_6;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class ObjectService {
|
||||
public void serviceMethod() throws InterruptedException {
|
||||
synchronized (this) {
|
||||
System.out.println("开始时间:" + LocalDateTime.now());
|
||||
TimeUnit.SECONDS.sleep(2);
|
||||
System.out.println("结束时间:" + LocalDateTime.now());
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package thead.thread_6;
|
||||
|
||||
public class Run {
|
||||
public static void main(String[] args) {
|
||||
// 因为使用的时同一个 ObjectService 所以代码是同步执行的
|
||||
ObjectService objectService = new ObjectService();
|
||||
ThreadA threadA = new ThreadA(objectService);
|
||||
threadA.setName("ThreadA");
|
||||
threadA.start();
|
||||
|
||||
ThreadB threadB = new ThreadB(objectService);
|
||||
threadB.setName("ThreadB");
|
||||
threadB.start();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package thead.thread_6;
|
||||
|
||||
import lombok.SneakyThrows;
|
||||
|
||||
public class ThreadA extends Thread {
|
||||
private final ObjectService objectService;
|
||||
|
||||
public ThreadA(ObjectService objectService) {
|
||||
super();
|
||||
this.objectService = objectService;
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
@Override
|
||||
public void run() {
|
||||
super.run();
|
||||
objectService.serviceMethod();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
package thead.thread_6;
|
||||
|
||||
import lombok.SneakyThrows;
|
||||
|
||||
public class ThreadB extends Thread {
|
||||
private final ObjectService objectService;
|
||||
|
||||
public ThreadB(ObjectService objectService) {
|
||||
super();
|
||||
this.objectService = objectService;
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
@Override
|
||||
public void run() {
|
||||
super.run();
|
||||
objectService.serviceMethod();
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue