今天學了多線程,雖然還不是很清楚多線程,但是多多少少了解了一些,現在試着給大家跟大家分享一下。由於水平有限,如果有錯誤的地方,還請多多指正。
那麼,JAVA中的多線程是怎樣實現的呢?當然它可以通過兩種方法實現,一種便是直接繼承Thread類,而第二種,也是比較常用的便是定義一個實現Runnable接口的類。
1.直接繼承Thread類
public class LerThread extends Thread {
public void run(){
for (char ch='a';ch<'f';ch++){
System.out.println("字母是:"+ch);
try{
Thread.sleep(101);
}
catch (InterruptedException e){
System.out.println(e.getMessage());
}
}
}
}
public class numTread extends Thread{
public void run(){
for (int i=0;i<5;i++){
System.out.println("數字是:"+i);
try{
Thread.sleep(50);
}
catch (InterruptedException e){
System.out.println(e.getMessage());
}
}
}
}
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread ld=new Thread(new LerThread());
Thread nT=new Thread(new numTread());
ld.start();
nT.start();
}
}
運行結果:
字母是:a
數字是:0
數字是:1
數字是:2
字母是:b
數字是:3
數字是:4
字母是:c
字母是:d
字母是:e
start()爲線程啓動的語句,而啓動後的線程所執行的操作則由run()方法來決定。在這個程序中,sleep()線程每次休眠的時間,通過讓線程的休眠時間不同,我們便可以瞭解多線程的工作。
可以看運行結果,我們發現數由於寫字母的LerThread線程的休眠時間爲101ms,所以在此期間數字能夠運行兩次。所以可以知道各線程之間的運行是獨立的。
2.通過定義Runnable接口的類來實現
public class LerThread implements Runnable {
public void run(){
for (char ch='a';ch<'f';ch++){
System.out.println("字母是:"+ch);
try{
Thread.sleep(101);
}
catch (InterruptedException e){
System.out.println(e.getMessage());
}
}
}
}
public class numTread implements Runnable{
public void run(){
for (int i=0;i<5;i++){
System.out.println("數字是:"+i);
try{
Thread.sleep(50);
}
catch (InterruptedException e){
System.out.println(e.getMessage());
}
}
}
}
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread ld=new Thread(new LerThread());
Thread nT=new Thread(new numTread());
ld.start();
nT.start();
}
}
運行結果:
字母是:a
數字是:0
數字是:1
數字是:2
字母是:b
數字是:3
數字是:4
字母是:c
字母是:d
字母是:e
通過定義Runnable接口,也可以達到多線程的目的,而且由於JAVA不支持*多重繼承,所以這也是比較常有的多線程實現方式。