八:多线程的几种实现方式及使用Runnable接口的优势

一、继承Thread类创建线程

重写run方法,用start启动线程

public class MyThread extends Thread {  
  public void run() {  
   System.out.println("MyThread.run()");  
  }  
}  
 
MyThread myThread1 = new MyThread();  
MyThread myThread2 = new MyThread();  
myThread1.start();  
myThread2.start();

二、实现Runnable方法创建线程

public class MyThread implements Runnable {  
  public void run() {  
   System.out.println("MyThread.run()");  
  }  
}

为了启动MyThread,需要首先实例化一个Thread,并传入自己的MyThread实例:

MyThread myThread = new MyThread();  
Thread thread = new Thread(myThread);  
thread.start(); 

三、实现Callable接口通过FutureTask包装器来创建Thread线程

public class SomeCallable<V> implements Callable<V> {

    @Override
    public V call() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

}
Callable<V> oneCallable = new SomeCallable<V>();   
//由Callable<Integer>创建一个FutureTask<Integer>对象:   
FutureTask<V> oneTask = new FutureTask<V>(oneCallable);   
//注释:FutureTask<Integer>是一个包装器,它通过接受Callable<Integer>来创建,它同时实现了Future和Runnable接口。 
  //由FutureTask<Integer>创建一个Thread对象:   
Thread oneThread = new Thread(oneTask);   
oneThread.start();   

四、创建线程池

public class Thread04 {
    
    private static int POOL_NUM =10;
    
    public static void main(String[] args)throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < POOL_NUM; i++) {
            RunnableThread  runnable =new  RunnableThread ();             
            executorService.execute(runnable);
        }
        executorService.shutdown();
    }


}
class RunnableThread  implements Runnable{     
    @Override
    public void run()  
    {  
          System.out.println("4--通过线程池创建的线程:" + Thread.currentThread().getName() + " "); 
    }  
}

实现Runnable接口比继承Thread类所具有的优势:

(1)适合多个相同的程序代码的线程去处理同一个资源

(2)可以避免java中的单继承的限制

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值