thread object generated from other class

Viewed 25

I want to generate this output.

cersei starts the race. jamie starts the race. tyrion starts the race. cersei 0 crossed obstacles. jamie 0 crossed obstacles. tyrion 0 crossed obstacles. cersei 1 crossed obstacles. jamie 1 crossed obstacles. tyrion 1 crossed obstacles. cersei 2 crossed obstacles. jamie 2 crossed obstacles. tyrion 2 crossed obstacles. cersei finishes the race.
jamie finishes the race.
tyrion finishes the race.

I can modify the player class.

class Player implements Runnable{
    Thread t;
}
class Competition{
    public static void main(String[] args){
        Player player1 = new Player("Cercei");
        Player player2 = new Player("Jamie");
        Player player3 = new Player("Tyrion");
    }
}

here is my try:

class Player implements Runnable
{
       
        String n;
        Player(String n)
        {
            this.n = n;
        }

        public void run() 
        { 
         
         Thread.currentThread().setName(n);
            
         for(int i = 0; i < 2; i++) 
         { 
            System.out.println( Thread.currentThread().getName() +" Thread is Running"); 
            try
             { 
                         Thread.currentThread().sleep(100); 
             } 
            
            catch(InterruptedException e) 
             { 
                          e.printStackTrace(); 
             } 
          } 
        System.out.println(Thread.currentThread().getName() +" thread is finished"); 
        } 
        
        public static void main(String args[])  
        {    
   
           Thread t = new Thread();    
           t.start();    
        }    
        
}
   
    public class Main{
        public static void main(String[] args){
            Player player1 = new Player("Cercei");
            Player player2 = new Player("Jamie");
            Player player3 = new Player("Tyrion");
        }
    }

no output showed. where is my problem? I hadn't written the output line yet, just checking the thread running perfectly. I am creating the thread from the main method of player class.

1 Answers

You can use ExecutorService to start your Runnables

        ExecutorService executors = Executors.newFixedThreadPool(3);
        executors.submit(player1);
        executors.submit(player2);
        executors.submit(player3);
Related