ºìÁªLinuxÃÅ»§
Linux°ïÖú

¶àÏß³Ìѧϰ³õ²½

·¢²¼Ê±¼ä:2006-05-03 18:54:48À´Ô´:ºìÁª×÷Õß:ºãÉÆϲ
import java.io.*;
//¶àÏ̱߳à³Ì
public class MultiThread
{
public static void main(String args[])
{
System.out.println("ÎÒÊÇÖ÷Ïß³Ì!");
//ÏÂÃæ´´½¨Ïß³ÌʵÀýthread1
ThreadUseExtends thread1=new ThreadUseExtends();
//´´½¨thread2ʱÒÔʵÏÖÁËRunnable½Ó¿ÚµÄTHhreadUseRunnableÀàʵÀýΪ²ÎÊý
Thread thread2=new Thread(new ThreadUseRunnable(),"SecondThread");
thread1.start();//Æô¶¯Ïß³Ìthread1ʹ֮´¦ÓÚ¾ÍÐ÷״̬
//thread1.setPriority(6);//ÉèÖÃthread1µÄÓÅÏȼ¶Îª6
//ÓÅÏȼ¶½«¾ö¶¨cpu¿Õ³öʱ£¬´¦ÓÚ¾ÍÐ÷״̬µÄÏß³ÌË­ÏÈÕ¼Áìcpu¿ªÊ¼ÔËÐÐ
//ÓÅÏȼ¶·¶Î§1µ½10,MIN_PRIORITY,MAX_PRIORITY,NORM_PAIORITY
//ÐÂÏ̼̳߳д´½¨ËýµÄ¸¸Ïß³ÌÓÅÏȼ¶,¸¸Ïß³Ìͨ³£ÓÐÆÕͨÓÅÏȼ¶¼´5NORM_PRIORITY
System.out.println("Ö÷Ï߳̽«¹ÒÆð7Ãë!");
try
{
Thread.sleep(7000);//Ö÷Ï̹߳ÒÆð7Ãë
}
catch (InterruptedException e)
{
return;
}
System.out.println("Óֻص½ÁËÖ÷Ïß³Ì!");
if(thread1.isAlive())
{
thread1.stop();//Èç¹ûthread1»¹´æÔÚÔòɱµôËû
System.out.println("thread1ÐÝÃß¹ý³¤,Ö÷Ïß³ÌɱµôÁËthread1!");
}
else
System.out.println("Ö÷Ïß³Ìû·¢ÏÖthread1,thread1ÒÑÐÑ˳ÐòÖ´ÐнáÊøÁË!");
thread2.start();//Æô¶¯thread2
System.out.println("Ö÷Ïß³ÌÓÖ½«¹ÒÆð7Ãë!");
try
{
Thread.sleep(7000);//Ö÷Ï̹߳ÒÆð7Ãë
}
catch (InterruptedException e)
{
return;
}
System.out.println("Óֻص½ÁËÖ÷Ïß³Ì!");
if(thread2.isAlive())
{
thread2.stop();//Èç¹ûthread2»¹´æÔÚÔòɱµôËû
System.out.println("thread2ÐÝÃß¹ý³¤£¬Ö÷Ïß³ÌɱµôÁËthread2!");
}
else
System.out.println("Ö÷Ïß³Ìû·¢ÏÖthread2,thread2ÒÑÐÑ˳ÐòÖ´ÐнáÊøÁË!");
System.out.println("³ÌÐò½áÊø°´ÈÎÒâ¼ü¼ÌÐø!");
try
{
System.in.read();
}
catch (IOException e)
{
System.out.println(e.toString());
}

}//main
}//MultiThread


class ThreadUseExtends extends Thread
//ͨ¹ý¼Ì³ÐThreadÀà,²¢ÊµÏÖËüµÄ³éÏó·½·¨run()
//Êʵ±Ê±ºò´´½¨ÕâÒ»Thread×ÓÀàµÄʵÀýÀ´ÊµÏÖ¶àÏ̻߳úÖÆ
//Ò»¸öÏß³ÌÆô¶¯ºó£¨Ò²¼´½øÈë¾ÍÐ÷״̬£©Ò»µ©»ñµÃCPU½«×Ô¶¯µ÷ÓÃËüµÄrun()·½·¨
{

ThreadUseExtends(){}//¹¹Ô캯Êý
public void run()
{
System.out.println("ÎÒÊÇThread×ÓÀàµÄÏß³ÌʵÀý!");
System.out.println("ÎÒ½«¹ÒÆð10Ãë!");
System.out.println("»Øµ½Ö÷Ïß³Ì,ÇëÉÔµÈ,¸Õ²ÅÖ÷Ï̹߳ÒÆð¿ÉÄÜ»¹Ã»ÐѹýÀ´£¡");
try
{
sleep(10000);//¹ÒÆð5Ãë
}
catch (InterruptedException e)
{
return;
}
//Èç¹û¸Ãrun()·½·¨Ë³ÐòÖ´ÐÐÍêÁË,Ï߳̽«×Ô¶¯½áÊø,¶ø²»»á±»Ö÷Ïß³Ìɱµô
//µ«Èç¹ûÐÝÃßʱ¼ä¹ý³¤,ÔòÏ̻߳¹´æ»î,¿ÉÄܱ»stop()ɱµô
}
}


class ThreadUseRunnable implements Runnable
//ͨ¹ýʵÏÖRunnable½Ó¿ÚÖеÄrun()·½·¨,ÔÙÒÔÕâ¸öʵÏÖÁËrun()·½·¨µÄÀà
//Ϊ²ÎÊý´´½¨ThreadµÄÏß³ÌʵÀý
{
//Thread thread2=new Thread(this);
//ÒÔÕâ¸öʵÏÖÁËRunnable½Ó¿ÚÖÐrun()·½·¨µÄÀàΪ²ÎÊý´´½¨ThreadÀàµÄÏß³ÌʵÀý
ThreadUseRunnable(){}//¹¹Ô캯Êý
public void run()
{
System.out.println("ÎÒÊÇThreadÀàµÄÏß³ÌʵÀý²¢ÒÔʵÏÖÁËRunnable½Ó¿ÚµÄÀàΪ²ÎÊý!");
System.out.println("ÎÒ½«¹ÒÆð1Ãë!");
System.out.println("»Øµ½Ö÷Ïß³Ì,ÇëÉÔµÈ,¸Õ²ÅÖ÷Ï̹߳ÒÆð¿ÉÄÜ»¹Ã»ÐѹýÀ´£¡");
try
{
Thread.sleep(1000);//¹ÒÆð5Ãë
}
catch (InterruptedException e)
{
return;
}
//Èç¹û¸Ãrun()·½·¨Ë³ÐòÖ´ÐÐÍêÁË,Ï߳̽«×Ô¶¯½áÊø,¶ø²»»á±»Ö÷Ïß³Ìɱµô
//µ«Èç¹ûÐÝÃßʱ¼ä¹ý³¤,ÔòÏ̻߳¹´æ»î,¿ÉÄܱ»stop()ɱµô
}

}
//¸Ã³ÌÐò¿É×öµÄÐÞ¸ÄÈç¸ÄÐÝÃßʱ¼ä»òÓÅÏȼ¶setPriority()
ÎÄÕÂÆÀÂÛ

¹²ÓÐ 0 ÌõÆÀÂÛ