4.02.线程的创建方式

2019-01-09  本文已影响0人  RockyLuo_290f

第一种,继承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();
上一篇 下一篇

猜你喜欢

热点阅读