第一种,继承Thread,
声明类为Thread的子类,并重写run
启动时调用start()
public class CountThread extends Thread{
//给线程命名
//public CountThread(String str){
// super(str);
//}
@Override
public void run(){
for(int i=0; i<50; i++){
System.out.println(this.getName()+" "+ i);
}
}
}
CountThread ct = new CountThread();
//CountThread ct = new CountThread("Thread 1");
//启动线程
ct.start();
第二种 实现Runnable
由于类继承只有一个,而接口实现多种,
所以第二种更常见
public class CountThreadB implements Runnable{
@Override
public void run() {
for(int i=0; i<50; i++){
System.out.println(Thread.currentThread().getName() + " ---"+i);
}
}
}
CountThreadB ct = new CountThreadB();
//Thread t1 = new Thread(ct);
//线程命名
Thread t1 = new Thread(ct,"process1");
CountThreadB ct2 = new CountThreadB();
// Thread t2 = new Thread(ct2);
Thread t2 = new Thread(ct2, "process2");
t1.start();
t2.start();
网友评论