我的任务是使 3 个(A、B、C)服务相互依赖。当服务A启动时,服务B可以启动,当服务B启动时,服务C可以启动,当C停止时,B可以停止,当B停止时,A可以停止。我已经设法启动线程并使用状态选项从一个切换到另一个。我不得不说我对java不太了解,但我刚刚开始学习java,所以我是新手,所以任何帮助、建议等都会很棒。
另外我有 3 个几乎相同的课程,所以任何人都可以告诉他们我如何用一个替换这 3 个课程?有什么办法吗?
这是我的代码:
public class service_class {
int status=1;
public static void main(String[] args) {
service_class service_class = new service_class();
A1 a=new A1(service_class);
B1 b=new B1(service_class);
C1 c=new C1(service_class);
a.start();
b.start();
c.start();
}
}
class A1 extends Thread{
service_class service_class;
A1(service_class service_class){
this.service_class = service_class;
}
@Override
public void run() {
try{
synchronized (service_class) {
while(service_class.status!=1){
service_class.wait();
}
System.out.print("A started" + "\n");
service_class.status = 2;
service_class.notifyAll();
while(service_class.status!=7){
service_class.wait();
}
System.out.print("A stoped" + "\n");
service_class.status = 1;
service_class.notifyAll();
}
}catch (Exception e) {
System.out.println("Exception 1 :"+e.getMessage());
}
}
}
class B1 extends Thread{
service_class service_class;
B1(service_class service_class){
this.service_class = service_class;
}
@Override
public void run() {
try{
synchronized (service_class) {
while(service_class.status!=2){
service_class.wait();
}
System.out.print("B started " + "\n");
service_class.status = 4;
service_class.notifyAll();
while(service_class.status!=6){
service_class.wait();
}
System.out.print("B stoped" + "\n");
service_class.status = 7;
service_class.notifyAll();
}
}catch (Exception e) {
System.out.println("Exception 2 :"+e.getMessage());
}
}
}
class C1 extends Thread{
service_class service_class;
C1(service_class service_class){
this.service_class = service_class;
}
@Override
public void run() {
try{
synchronized (service_class) {
while(service_class.status!=4){
service_class.wait();
}
System.out.print("C started" + "\n");
service_class.status = 5;
service_class.notifyAll();
while(service_class.status!=5){
service_class.wait();
}
System.out.print("C stoped" + "\n");
service_class.status = 6;
service_class.notifyAll();
}
}catch (Exception e) {
System.out.println("Exception 4 :"+e.getMessage());
};
}
}