1.是什么?
- 多線程,是一個(gè)進(jìn)程同一時(shí)間段,執(zhí)行多個(gè)代碼段
- 為了盡可能的利用系統(tǒng)資源。
- 線程執(zhí)行過(guò)程:
創(chuàng)建new Thread();
就緒new Thread().start();
阻塞new Thread().sleep(400);
運(yùn)行 繼承Thread方法時(shí)extends Thread;需重寫(xiě)的代碼run()方法
死亡new Thread().stop();
2.怎么做?
繼承thread類(lèi)
class ThreadExtends extends Thread {
private String name;
public ThreadExtends(String name){
this.name = name;
}
public void run(){ //運(yùn)行
for(int i=0; i<10; i++){
System.out.println(this.name+" : "+i);
}
}
}
public class testDemo{
public static void main(String arg[]){
ThreadExtends thread1 = new ThreadExtends("thread1");//創(chuàng)建
ThreadExtends thread2 = new ThreadExtends("thread2");
thread1.start();//就緒
thread2.start();
}
}
extends Thread運(yùn)行結(jié)果:
thread1 : 0
thread1 : 1
thread1 : 2
thread1 : 3
thread2 : 0
thread2 : 1
thread2 : 2
thread2 : 3
thread2 : 4
thread2 : 5
thread2 : 6
thread2 : 7
thread2 : 8
thread2 : 9
thread1 : 4
thread1 : 5
thread1 : 6
thread1 : 7
thread1 : 8
thread1 : 9
實(shí)現(xiàn)Runnable接口
class ThreadImplements implements Runnable {
private String name;
public ThreadImplements(String name){
this.name = name;
}
public void run(){
for(int i=0; i<10; i++){
System.out.println(this.name+" : "+i);
}
}
}
public class testDemo{
public static void main(String arg[]){
ThreadImplements threadImp1 = new ThreadImplements("thread1");
ThreadImplements threadImp2 = new ThreadImplements("thread2");
Thread thread1 = new Thread(threadImp1);
Thread thread2 = new Thread(threadImp2);
thread1.start();
thread2.start();
}
}
implements Runnable運(yùn)行結(jié)果:
thread2 : 0
thread2 : 1
thread2 : 2
thread2 : 3
thread2 : 4
thread2 : 5
thread2 : 6
thread2 : 7
thread2 : 8
thread2 : 9
thread1 : 0
thread1 : 1
thread1 : 2
thread1 : 3
thread1 : 4
thread1 : 5
thread1 : 6
thread1 : 7
thread1 : 8
thread1 : 9