程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> java多線程學習初步

java多線程學習初步

編輯:關於JAVA

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()

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved