feat: synchronized-2
This commit is contained in:
parent
8a8881fd03
commit
e90294d7d6
|
@ -0,0 +1,12 @@
|
||||||
|
package thead.thread_7;
|
||||||
|
|
||||||
|
public class Run {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
Service service = new Service();
|
||||||
|
ThreadA threadA = new ThreadA(service);
|
||||||
|
threadA.start();
|
||||||
|
|
||||||
|
ThreadB threadB = new ThreadB(service);
|
||||||
|
threadB.start();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
package thead.thread_7;
|
||||||
|
|
||||||
|
public class Service {
|
||||||
|
public synchronized static void methodB() {
|
||||||
|
synchronized (Service.class) {
|
||||||
|
System.out.println("B方法开始");
|
||||||
|
System.out.println("B方法结束");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void methodA() {
|
||||||
|
synchronized (this) {
|
||||||
|
System.out.println("A方法开始");
|
||||||
|
boolean b = true;
|
||||||
|
while (b) {
|
||||||
|
|
||||||
|
}
|
||||||
|
System.out.println("A方法结束");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,23 @@
|
||||||
|
package thead.thread_7;
|
||||||
|
|
||||||
|
public class ThreadA extends Thread {
|
||||||
|
|
||||||
|
public Service service;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Allocates a new {@code Thread} object. This constructor has the same
|
||||||
|
* effect as {@linkplain #Thread(ThreadGroup, Runnable, String) Thread}
|
||||||
|
* {@code (null, null, gname)}, where {@code gname} is a newly generated
|
||||||
|
* name. Automatically generated names are of the form
|
||||||
|
* {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
|
||||||
|
*/
|
||||||
|
public ThreadA(Service service) {
|
||||||
|
super.run();
|
||||||
|
this.service = service;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
service.methodA();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,22 @@
|
||||||
|
package thead.thread_7;
|
||||||
|
|
||||||
|
public class ThreadB extends Thread {
|
||||||
|
|
||||||
|
private final Service service;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Allocates a new {@code Thread} object. This constructor has the same
|
||||||
|
* effect as {@linkplain #Thread(ThreadGroup, Runnable, String) Thread}
|
||||||
|
* {@code (null, null, gname)}, where {@code gname} is a newly generated
|
||||||
|
* name. Automatically generated names are of the form
|
||||||
|
* {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
|
||||||
|
*/
|
||||||
|
public ThreadB(Service service) {
|
||||||
|
this.service = service;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
service.methodB();
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue