thread 是描述線程的一個(gè)類,你可以創(chuàng)建一個(gè)類繼承Thread這個(gè)類,通過你創(chuàng)建的類開辟線程,獲取線程的名字,讓線程停留等等。
第一種定義線程方式:
class People extends Thread{
public void run(){
for(int i=0;i<10;i++){
System.out.println("i="+i);
}
}
}
class Demo {
public static void main(String[] args) {
People p=new People();
People p2=new People();
p.start();
p2.start();
}
}
第二種定義線程方式:
class Ticket implements Runnable {
int num = 20;
public void run() {
while (true) {
if (num > 0) {
System.out.println(Thread.currentThread().getName() + "-----num=" + num--);
}
}
}
}
class Demo {
public static void main(String[] args) {
Ticket t = new Ticket();
Thread tt = new Thread(t);
Thread tt1 = new Thread(t);
Thread tt2 = new Thread(t);
tt.start();
tt1.start();
tt2.start();
}
}