java Thread:利用Thread類實現多線程

 public class UsingThread {

 /**
  * @param args
  */
 
 //創建一個新進程類
 /*public static void main(String[] args) {
  // TODO Auto-generated method stub
  System.out.println("main thread started");
  FactorialThread2 f=new FactorialThread2(10);
  f.start();
  System.out.println("main thread end");
 }
}//usingthread
    class FactorialThread2 extends Thread
    {
     private int num;
     public FactorialThread2(int num)
     {
      this.num=num;
     }
     
     public void run()
     {
      int i=num;
      int result=1;
      System.out.println("new thread started");
      while(i>0)
       {result*=i;
            i-=1;}
      System.out.println("The factorial of"+num+"is"+result);
      System.out.println("new thread ends");
     }
     */
 
 
 //創建3個新線程,每個線程睡眠一段時間(0~6秒),然後結束
 public static void main(String[] args)
 {
  System.out.println("Starting thread");
  TestTread t1=new TestTread("t1");
  TestTread t2=new TestTread("t2");
  TestTread t3=new TestTread("t3");
  t1.start();
  t2.start();
  t3.start();
  System.out.println("threads starts,main ends/n");
 }
}//usingTread
 class TestTread extends Thread
 {
  private int sleepTime;
  public TestTread(String name)
  {
   super(name);
   sleepTime=(int)(Math.random()*6000);
   
  }
  public void run(){
   try {
    System.out.println(this.getName()+" going to sleep for "+sleepTime);
    Thread.sleep(sleepTime);
   } catch (InterruptedException e) {}
    // TODO Auto-generated catch block
    System.out.println(getName()+" finished");
   
  }
 }
 /*心得:

1.從Thread類派生一個類,並創建這個類的對象,就可以產生一個新的線程

2.在派生類中需要重寫run()方法,

3.調用sleep(long)可以令線程暫停long ms

4.繼承Thread的派生類創建對象後,調用它的start()即可以運行一個新線程

*/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章