- Java多線程介紹 推薦度:
- 相關(guān)推薦
java多線程介紹
多線程的基本實現(xiàn)
進程指運行中的程序,每個進程都會分配一個內(nèi)存空間,一個進程中存在多個線程,啟動一個JAVA虛擬機,就是打開個一個進程,一個進程有多個線程,當(dāng)多個線程同時進行,就叫并發(fā)。
Java創(chuàng)建線程的兩種方式為: 繼承Thread類 和實現(xiàn)Runnable接口
Thread類
1、通過覆蓋run方法實現(xiàn)線程要執(zhí)行的程序代碼
2、Start()開始執(zhí)行多線程
package com.bin.duoxiancheng;
public class d1 extends Thread{
public void run(){
for(int i=0 ; i<50; i++){
System.out.println(i);
System.out.println(currentThread()。getName());
try {
sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
}
}
public static void main(String[] args){
new d1()。start();
new d1()。start();
}
}
多個線程共享一個實例的時候,代碼代碼如下:
package com.bin.duoxiancheng;
public class d1 extends Thread{
int i=0;
public void run(){
for(i=0 ; i<50; i++){
System.out.println(i);
System.out.println(currentThread()。getName());
try {
sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
}
}
public static void main(String[] args){
new d1()。start();
new d1()。start();
}
}
結(jié)果如下所示:
Thread-1
Thread-0
1
Thread-1
1
實際2個線程在操縱不同的變量a,在執(zhí)行run方法時候,線程把a都當(dāng)做自己的變量在執(zhí)行。
Runnable接口實現(xiàn)多線程
當(dāng)一個繼承自Thread時,就不能再繼承其他類,使用Runnable接口解決了此問題,在新建一個Thread類中,在構(gòu)造方法中初始化
Thread(Runnable target)
分配新的 Thread 對象。
Thread(Runnable target,String name)
分配新的 Thread 對象。
package com.bin.duoxiancheng;
public class D2 implements Runnable{
int i=0;
public void run(){
for(i=0 ; i<50; i++){
System.out.println(i);
System.out.println(Thread.currentThread()。getName());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
}
}
public static void main(String[] args){
D2 d=new D2();
Thread t=new Thread(d);
t.start();
}
}
【java多線程介紹】相關(guān)文章:
關(guān)于Java多線程介紹09-09
java多線程08-31
java的多線程09-09
java語言的多線程08-29
Java多線程的開發(fā)技巧10-16
Java多線程問題總結(jié)10-24
高級Java多線程面試題及回答06-08
java多線程同步塊實例講解素材08-28
舉例講解Java中的多線程范文欣賞06-16
JAVA多線程之線程間的通信方式解析07-14