Android开发经验谈Android开发Android技术知识

【Java】线程创建的四种方式

2019-06-29  本文已影响8人  秀叶寒冬

1 前言

线程创建线程的方法一般可以分为四类:

  1. 通过实现Runnable接口来创建Thread线程
  2. 通过实现Callable接口来创建Thread线程
  3. 通过继承Thread类来创建一个线程
  4. 使用Executor框架来创建线程

2 创建线程的四种方式

2.1 实现Runnable接口创建Thread

通过实现Runnable接口来创建Thread线程,其步骤可以分为以下几步

class TestRunnable implements Runnable{
    public void run(){
    }
}
Runnable testRunnable = new TestRunnable();
Thread testThread = new Thread(testRunnable);

步骤4:启动线程:

testThread.start();

至此,通过实现Runnable接口来创建线程的步骤完成。

代码实现如下所示:
(1)TestRunnable类

package com.yds.test;
public class TestRunnable implements Runnable {
    @Override
    public void run() {
        // TODO 自动生成的方法存根
        int i=0;
        while(i<10){
            System.out.println(i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
            i++;
        }
    }
}

(2)Test类调用

package com.yds.test;

public class Test {

    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        //使用实现Runnable接口创建线程
        Runnable testRunnable = new TestRunnable();
        Thread testThread = new Thread(testRunnable);
        testThread.start();
    }

}

2.2 实现Callable接口来创建Thread线程

Callable是一个接口,只有一个call方法,用Callable接口创建Thread线程的步骤如下:

package com.yds.test;

import java.util.concurrent.Callable;

public class TestCallable implements Callable<Integer>{

    @Override
    public Integer call() throws Exception {
        // TODO 自动生成的方法存根
        int i=0;
        while(i<10){
            System.out.println(i);
            Thread.sleep(1000);
            i++;
        }
        return i;
    }

}

TestCallable testCallable = new TestCallable();
FutureTask<Integer> task = new FutureTask<Integer>(testCallable);
Thread thread = new Thread(task);
thread.start();

FutureTask的get方法是返回Callable里的call返回的值,如果call方法里面是耗时任务,则get方法会阻塞主线程。

代码实现如下:
TestCallable类:

package com.yds.test;

import java.util.concurrent.Callable;

public class TestCallable implements Callable<Integer>{

    @Override
    public Integer call() throws Exception {
        // TODO 自动生成的方法存根
        int i=0;
        while(i<10){
            System.out.println(i);
            Thread.sleep(1000);
            i++;
        }
        return i;
    }

}

Test调用

package com.yds.test;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Test {

    public static void main(String[] args) {
        
        //1. 使用实现Runnable接口创建线程
//      Runnable testRunnable = new TestRunnable();
//      Thread testThread = new Thread(testRunnable);
//      testThread.start();
        
        
        //2. 使用Callable和Future创建线程
        TestCallable testCallable = new TestCallable();
        FutureTask<Integer> task = new FutureTask<Integer>(testCallable);
        Thread thread = new Thread(task);
        thread.start();     
    }

}

2.3 继承Thread类来创建线程

public class TestThread extends Thread{
    @Override
    public void run() {
        // TODO 自动生成的方法存根
        
    }
}
TestThread testThread = new TestThread();
testThread.start();

代码示例如下:

TestThread类

package com.yds.test;

public class TestThread extends Thread{
    @Override
    public void run() {
        // TODO 自动生成的方法存根
        int i = 0;
        while(i<10){
            System.out.println(i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
            i++;
        }
    }
}

Test调用

package com.yds.test;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Test {

    public static void main(String[] args) {
        
        //1. 使用实现Runnable接口创建线程
//      Runnable testRunnable = new TestRunnable();
//      Thread testThread = new Thread(testRunnable);
//      testThread.start();
        
        
        //2. 使用Callable和Future创建线程
//      TestCallable testCallable = new TestCallable();
//      FutureTask<Integer> task = new FutureTask<Integer>(testCallable);
//      Thread thread = new Thread(task);
//      thread.start();
        
        
        //3. 继承Thread创建线程
        TestThread testThread = new TestThread();
        testThread.start();
        
        
    }

}

2.4 使用Executor框架来创建线程池

Executors类中包含以下四个创建线程池方法。

方法名 描述
newCachedThreadPool() 创建一个可以缓存的线程池,如果线程池中有线程可用,则复用该线程,如果线程不可用,则创建一个新的线程并加入线程池中。终止并从缓存池中移除那些60秒未被使用的线程。
newFixedThreadPool 创建固定数目线程的线程池。
newSingleThreadExecutor 创建一个单线程化的Executor
newScheduledThreadPool 创建一个支持定时及周期性的任务执行的线程池,多数情况下可用来替代Timer类。
package com.yds.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

public class Test {

    public static void main(String[] args) {
        
        //1. 使用实现Runnable接口创建线程
//      Runnable testRunnable = new TestRunnable();
//      Thread testThread = new Thread(testRunnable);
//      testThread.start();
        
        
        //2. 使用Callable和Future创建线程
//      TestCallable testCallable = new TestCallable();
//      FutureTask<Integer> task = new FutureTask<Integer>(testCallable);
//      Thread thread = new Thread(task);
//      thread.start();
        
        
        //3. 继承Thread创建线程
//      TestThread testThread = new TestThread();
//      testThread.start();
        
        // 4. 使用Executor执行Runnable创建线程
        ExecutorService executorServicec = Executors.newCachedThreadPool();
        executorServicec.execute(new TestRunnable());
        executorServicec.shutdown();
        
    }

}

package com.yds.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

public class Test {

    public static void main(String[] args) {
        
        //1. 使用实现Runnable接口创建线程
//      Runnable testRunnable = new TestRunnable();
//      Thread testThread = new Thread(testRunnable);
//      testThread.start();
        
        
        //2. 使用Callable和Future创建线程
//      TestCallable testCallable = new TestCallable();
//      FutureTask<Integer> task = new FutureTask<Integer>(testCallable);
//      Thread thread = new Thread(task);
//      thread.start();
        
        
        //3. 继承Thread创建线程
//      TestThread testThread = new TestThread();
//      testThread.start();
        
        // 4. 使用Executor执行Runnable创建线程
//      ExecutorService executorServicec = Executors.newCachedThreadPool();
//      executorServicec.execute(new TestRunnable());
//      executorServicec.shutdown();
        
        //5. 使用Executor执行Callable创建线程
        ExecutorService executorServicec = Executors.newCachedThreadPool();
        TestCallable testCallable = new TestCallable();
        FutureTask<Integer> task = new FutureTask<Integer>(testCallable);
        
        executorServicec.execute(task);
        
    }

}

上一篇 下一篇

猜你喜欢

热点阅读