试试看派生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
}
}
}
[] [] [] [] [] [] [] []