码迷,mamicode.com
首页 > 编程语言 > 详细

java多线程的4种实现方式

时间:2018-07-17 10:48:30      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:实现   int   main   public   col   方法   adp   cut   dex   

1,继承Thread类,重写run方法;

public class Thread01 extends Thread{
    public Thread01(){
    }
    public void run(){  
        System.out.println(Thread.currentThread().getName());
    }
    public static void main(String[] args){ 
        Thread01 thread01 = new Thread01(); 
        thread01.setName("继承Thread类的线程1");
        thread01.start();       
        System.out.println(Thread.currentThread().toString());  
    }
}

2,实现Runnable接口,重写run方法;

public class Thread02 {

    public static void main(String[] args){ 
        System.out.println(Thread.currentThread().getName());
        Thread t2 = new Thread(new MyThread02());
        t2.start(); 
    }
}
class MyThread02 implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"2--实现Runnable接口的线程实现方式");
    }   
}

3,实现Callable接口通过FutureTask包装器来创建Thread线程;

 

4,通过线程池创建线程;

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() + " "); 
    }  
}  

 

java多线程的4种实现方式

标签:实现   int   main   public   col   方法   adp   cut   dex   

原文地址:https://www.cnblogs.com/yuiqng/p/9321648.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!