Can I have multiple run methods in a class?

前端 未结 5 718
眼角桃花
眼角桃花 2021-01-03 03:21

If so, how? I need to have 2 run methods in each object I will instantiate.

I meant a run method for threading.

What i need is more like a race of two cars.

5条回答
  •  有刺的猬
    2021-01-03 04:22

    Try:

     public class Car extends Thread
     {
          public String name;
    
          public Car(String name)
          {
               this.name = name;
          }
          public void run()
          {
               //your code
          }
     }
    
     public static void main(String[] args)
     {
          Thread car1 = new Car("car1's name");
          Thread car2 = new Car("car2's name");
          car1.start();
          car2.start();
    
     }
    

    You can add your logic into Car.run(), but basically that's how I would do that. In your logic determine when it starts and ends. When both threads finish, you can see which one is the winner. You could also add a while loop and have a field in Car that is a boolean type to determine if it's finished or not.

提交回复
热议问题