同時練習1

2008 ワード

  • /** 
  • *Javaプログラミング思想第4版c 21同時
  • *練習1:Runnableを実装し、run()内部にメッセージを印刷します.
  • *はyield()を呼び出し、この操作を3回繰り返しrunから返します. 
  • *構築中に起動メッセージを配置し、タスク終了
  • に配置する
  • *のクローズメッセージは、スレッドを使用して大量のタスクを作成し、駆動します. 
  •  */  
  • package threadtest;
    
    
    /**
     *
     * @author Administrator
     */
    
    
    public class ThreadTest {
    
    
        /**
         * @param args the command line arguments
         */
        public static class exercise implements Runnable
        {
    //        
            private int count ;
            public exercise(){}  
            public exercise(int count)
            {
                this.count = count;
                System.out.println("exercise"+count+" had been constructed");
            }
    
            public void run()
            {
                for(int i = 0;i < 3;i++)
                {
                    System.out.println("now in thread"+ i+" times");
                    Thread.yield();      
                }
                 System.out.println("end " + count);  
            
        }
    }
        public static void main(String[] args) {
            // TODO code application logic here
           for(int i=0; i<5; i++)
           {  
                new Thread(new exercise(i)).start();  
            } 
    }
    }
  • 生成結果(Netbeans ide) exercise0 had been constructed exercise1 had been constructed now in thread0 times now in thread1 times now in thread2 times end 0 exercise2 had been constructed exercise3 had been constructed exercise4 had been constructed now in thread0 times now in thread1 times now in thread2 times end 1 now in thread0 times now in thread1 times now in thread2 times end 3 now in thread0 times now in thread1 times now in thread2 times end 2 now in thread0 times now in thread1 times now in thread2 times end 4