【问题标题】:thread object generated from other class从其他类生成的线程对象
【发布时间】:2021-06-24 11:15:17
【问题描述】:

我想生成这个输出。

瑟曦开始比赛。 杰米开始比赛。 提利昂开始比赛。 瑟曦0越过障碍。 杰米 0 越过障碍。 提利昂 0 越过障碍。 瑟曦一号越过障碍。 杰米 1 越过障碍物。 提利昂 1 越过障碍。 瑟曦2越过障碍。 杰米 2 越过障碍。 提利昂 2 越过障碍。 瑟曦完成了比赛。
杰米完成了比赛。
提利昂完成了比赛。

我可以修改播放器类。

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");
    }
}

这是我的尝试:

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");
        }
    }

没有显示输出。我的问题在哪里? 我还没有写输出行,只是检查线程运行是否完美。 我正在从播放器类的 main 方法创建线程。

【问题讨论】:

    标签: java multithreading


    【解决方案1】:

    你可以使用 ExecutorService 来启动你的 Runnables

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      • 2018-09-09
      • 1970-01-01
      • 2021-03-24
      • 1970-01-01
      相关资源
      最近更新 更多