java多线程-四种实现方式

java中多线实现共有四种方式:

* 继承thread
* 实现runnable接口
* 通过callable和FutureTask创建线程
* 通过线程池

--

1. 继承thread类,重写run方法,该实现方式没有返回值。
 
 ```
 public class myThread extends Thread {
    //private int i = 0;
    public myThread() {
        System.out.println("myThread init");
    }
    public void run() {
        System.out.println(Thread.currentThread()+" is running ");
    }
    public static void main(String[] args) {
        myThread th= new myThread();
        th.start();
        myThread th1= new myThread();
        th1.start();
        System.out.println(Thread.currentThread());
    }
}
//myThread init
//myThread init
//Thread[Thread-0,5,main] is running 
//Thread[main,5,main]
//Thread[Thread-1,5,main] is running 
  ```
----

2. 如果自己的类继承了其他的类时,无法继承thread。此时可以通过implement runnable协议实现多线程。runnable 协议相比与thread很容易实现并发的多个线程共享资源。
 
 ```
 public class runnableTest implements Runnable {
    public void run() {
        System.out.println("runnable is running  " + Thread.currentThread());
    }
    public static void main(String[] args) {
        Thread thread = new Thread(new runnableTest());
        thread.start();
        System.out.println(Thread.currentThread());
        //runnableTest runnableTest = new runnableTest();
        //runnableTest.run();
        //此时runnable的任务分配给了主线程
    }
}
//Thread[main,5,main]
//runnable is running  Thread[Thread-0,5,main]
 ```
 ---
3. runnable接口是没有返回值的,而callable接口却有返回值,callable是一种具有类型参数的泛型,它的类型参数是call()方法的返回值。

```
class callableTask implements Callable<String> {
    
    private int id;
    public callableTask(int id) {
        // TODO Auto-generated constructor stub
        this.id = id;
    }    
    
    @Override
    public String call() throws Exception {
        return "result of callableTask" + id;
    }
}

public class CallableTest {

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        ArrayList<Future<String>> res = new ArrayList<Future<String>>() ;
        for (int i = 0; i < 10; i++) {
            res.add(exec.submit(new callableTask(i)));
        }
        for (Future<String> future : res) {
            try {
                System.out.println(future.get());
            } catch (Exception e) {
                // TODO: handle exception
                System.out.println();
            }finally {
                exec.shutdown();
            }
        }
    }
    
}
//result of callableTask0
//result of callableTask1
//result of callableTask2
//result of callableTask3
//result of callableTask4
//result of callableTask5
//result of callableTask6
//result of callableTask7
//result of callableTask8
//result of callableTask9

```
4. 通过线程池来实现多线程。CachedThreadPool、FixThreadPool、SingleThreadPool。


```

public class executorTest {
    

     public static void main(String[] args) throws InterruptedException {
            // TODO Auto-generated method stub
            ExecutorService executorService = Executors.newFixedThreadPool(5);  
            for(int i = 0; i<10; i++)  
            {  
                RunnableThread thread = new RunnableThread();
                executorService.execute(thread);  
            }
            //关闭线程池
            executorService.shutdown(); 

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

    }  
}  
//通过线程池方式创建的线程:pool-1-thread-3 
//通过线程池方式创建的线程:pool-1-thread-2 
//通过线程池方式创建的线程:pool-1-thread-3 
//通过线程池方式创建的线程:pool-1-thread-5 
//通过线程池方式创建的线程:pool-1-thread-4 
//通过线程池方式创建的线程:pool-1-thread-1 
//通过线程池方式创建的线程:pool-1-thread-4 
//通过线程池方式创建的线程:pool-1-thread-5 
//通过线程池方式创建的线程:pool-1-thread-3 
//通过线程池方式创建的线程:pool-1-thread-2 

``` 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 继承Thread类 Java提供了Thread类,我们可以通过继承Thread类来实现多线程。具体步骤如下: (1)创建一个继承Thread类的子类,并重写run()方法。 (2)在子类中创建一个Thread类的实例对象,并调用start()方法启动线程。 示例代码如下: ``` public class MyThread extends Thread { @Override public void run() { // 线程执行的代码 } } // 创建线程并启动 MyThread myThread = new MyThread(); myThread.start(); ``` 2. 实现Runnable接口 Java中还可以通过实现Runnable接口来实现多线程。具体步骤如下: (1)创建一个实现Runnable接口的类,并实现run()方法。 (2)在类中创建一个Thread类的实例对象,将实现了Runnable接口的类的实例对象作为参数传入Thread的构造方法中。 (3)调用Thread实例对象的start()方法启动线程。 示例代码如下: ``` public class MyRunnable implements Runnable { @Override public void run() { // 线程执行的代码 } } // 创建线程并启动 MyRunnable myRunnable = new MyRunnable(); Thread thread = new Thread(myRunnable); thread.start(); ``` 3. 实现Callable接口 Java中还可以通过实现Callable接口来实现多线程。与实现Runnable接口相比,实现Callable接口可以有返回值,并且可以抛出异常。具体步骤如下: (1)创建一个实现Callable接口的类,并实现call()方法。 (2)创建一个ExecutorService线程池对象,调用submit()方法提交Callable类的实例对象。 (3)调用Future类的get()方法获取线程执行结果。 示例代码如下: ``` public class MyCallable implements Callable<Integer> { @Override public Integer call() throws Exception { // 线程执行的代码 return 1; } } // 创建线程池对象 ExecutorService executorService = Executors.newFixedThreadPool(1); // 提交Callable实例对象 MyCallable myCallable = new MyCallable(); Future<Integer> future = executorService.submit(myCallable); // 获取线程执行结果 int result = future.get(); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值