熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java高級技術 >> 正文

Java2入門經典教程 11.1 了解線程[3]

2022-06-13   來源: Java高級技術 

    試試看派生Thread的子類

    用一個例子我們可以看到這是如何工作的我們將定義一個由Thread的類派生的類TryThread執行從main()方法開始

import javaioTOException;
public java TryThread extends thread
{
private string firstName;                    //store for first name
private string secondName;                  //store for second name
private long awhile                        //Delay in milliseconds
public TryThread(string firsNamestring secondName long delay
{
thisfirstName=firstName                  //store the first name
thissecondName=secondName;              //store the second name
awhile=delay                            //store the delay
setDaemon(true)                        //Thread is daemon
}
public static void main (string[]args)
{
//create three threads
Thread first =new TryThread(HopalongcassidyL);
Thread second=new TryThread(MarilynMonroeL);
Thread third =new TryThread(slimpickensL);
systemoutprintln(press Enter when you have had enough\n);
firststart();                           //start the first thread
secondstart();                         //start the second thread
thridstart();              //start the thrid thread
try
{
  systeminread();        //wait until Enter key pressed
  systemoutprintln(Enter prosed\n);
 }
 catch (IOException e)    //Hand Io exception
  {
    systemoutprintln(e);      //Output the exception
  }
  systemoutprintln(Ending main());
  return;
  //Method where thread execption will stare
  public void run()
  {
    try
     {
      while(ture)              //Loop indefinitely
       {
      systemoutprin(firstName);     //output first name
     sleep(awhile);                   //wait awhile mses
     systemoutprint(secondName + \n);  //output second name
   }
  }
  catch(InteruptedException e)           //Hand thread interruption
  {
    systemoutprintln(firstName+secondName+e);     //Output the exception
   }
  }
}

[]  []  []  []  []  []  []  []  


From:http://tw.wingwit.com/Article/program/Java/gj/201311/27755.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.