创建线程的四种方式

1. 线程的创建有四种方式

2. 继承Thread类

3. 实现Runnable接口

4.实现Callable接口

5.线程池创建线程


1. 线程的创建有四种方式,分别为:

  • 继承Thread类
  • 实现Runnable接口
  • 实现Callable接口
  • 使用Executor框架创建线程池

编写多线程程序是为了实现多任务的并发执行,从而能够更好地与用户交互。一般有四种方法,Thread,Runnable,Callable,使用Executor框架来创建线程池。

Runnable和Callable的区别是:
(1)Callable规定的方法是call(),Runnable规定的方法是run().
(2)Callable的任务执行后可返回值,而Runnable的任务是不能返回值得
(3)call方法可以抛出异常,run方法不可以
(4)运行Callable任务可以拿到一个Future对象,表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。通过Future对象可以了解任务执行情况,可取消任务的执行,还可获取执行结果。

2. 继承Thread类

public class ThreadTEST {
    public static void main(String[] args) {
        Thread.currentThread().setName("main thread");
        MyThread myThread1 = new MyThread();
        MyThread myThread2 = new MyThread();

        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "前面" + i);
        }

        myThread1.setName("sub Thread A:");
        myThread2.setName("sub Thread B:");

        myThread1.start();
        myThread2.start();
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + "后面" + i);
        }
    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + i);
        }
    }
}


// 打印结果(不唯一):
/*
main thread前面0
main thread前面1
main thread前面2
main thread前面3
main thread前面4
main thread前面5
main thread前面6
main thread前面7
main thread前面8
main thread前面9
main thread后面0
main thread后面1
main thread后面2
main thread后面3
main thread后面4
main thread后面5
main thread后面6
main thread后面7
main thread后面8
main thread后面9
main thread后面10
main thread后面11
main thread后面12
main thread后面13
main thread后面14
main thread后面15
main thread后面16
sub Thread A:0
sub Thread A:1
main thread后面17
main thread后面18
main thread后面19
main thread后面20
main thread后面21
main thread后面22
main thread后面23
main thread后面24
sub Thread B:0
sub Thread B:1
sub Thread B:2
sub Thread B:3
sub Thread A:2
sub Thread A:3
sub Thread B:4
main thread后面25
sub Thread A:4
main thread后面26
main thread后面27
main thread后面28
main thread后面29
......
main thread后面99

Process finished with exit code 0
Process finished with exit code 0
*/

3. 实现Runnable接口

//实现Runnable接口
public class RunnableTest {

    public static void main(String[] args) {
        //设置线程名字
        Thread.currentThread().setName("main thread:");
        Thread thread = new Thread(new MyRunnable());
        thread.setName("子线程:");
        //开启线程
        thread.start();
        for(int i = 0; i <5;i++){
            System.out.println(Thread.currentThread().getName() + i);
        }
    }
}

class MyRunnable implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + i);
        }
    }
}
// 打印结果(不唯一):
/*
main thread:0
子线程:0
main thread:1
main thread:2
main thread:3
main thread:4
子线程:1
子线程:2
子线程:3
子线程:4
子线程:5
子线程:6
子线程:7
子线程:8
子线程:9

Process finished with exit code 0
*/

4.实现Callable接口

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
//实现Callable接口
public class CallableTest {

    public static void main(String[] args) {
        //执行Callable 方式,需要FutureTask 实现实现,用于接收运算结果
        FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyCallable());
        new Thread(futureTask).start();
        //接收线程运算后的结果
        try {
            Integer sum = futureTask.get();
            System.out.println(sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

class MyCallable implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            sum += i;
        }
        return sum;
    }
}

//结果:
/*
4950

Process finished with exit code 0
*/

5.线程池创建线程

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//线程池实现
public class ThreadPoolExecutorTest {

    public static void main(String[] args) {
        //创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        ThreadPool threadPool = new ThreadPool();
        for(int i =0;i<5;i++){
            //为线程池分配任务
            executorService.submit(threadPool);
        }
        //关闭线程池
        executorService.shutdown();
    }
}

class ThreadPool implements Runnable {

    @Override
    public void run() {
        for(int i = 0 ;i<10;i++){
            System.out.println(Thread.currentThread().getName() + ":" + i);
        }
    }

}

// 打印结果(不唯一):
/*
pool-1-thread-1:0
pool-1-thread-2:0
pool-1-thread-2:1
pool-1-thread-3:0
pool-1-thread-3:1
pool-1-thread-3:2
pool-1-thread-2:2
pool-1-thread-2:3
pool-1-thread-2:4
pool-1-thread-2:5
pool-1-thread-1:1
pool-1-thread-5:0
pool-1-thread-5:1
pool-1-thread-5:2
pool-1-thread-5:3
pool-1-thread-2:6
pool-1-thread-2:7
pool-1-thread-2:8
pool-1-thread-3:3
pool-1-thread-2:9
pool-1-thread-5:4
pool-1-thread-4:0
pool-1-thread-4:1
pool-1-thread-1:2
pool-1-thread-1:3
pool-1-thread-1:4
pool-1-thread-1:5
pool-1-thread-1:6
pool-1-thread-1:7
pool-1-thread-1:8
pool-1-thread-1:9
pool-1-thread-4:2
pool-1-thread-4:3
pool-1-thread-4:4
pool-1-thread-4:5
pool-1-thread-5:5
pool-1-thread-3:4
pool-1-thread-3:5
pool-1-thread-3:6
pool-1-thread-3:7
pool-1-thread-3:8
pool-1-thread-3:9
pool-1-thread-5:6
pool-1-thread-4:6
pool-1-thread-5:7
pool-1-thread-4:7
pool-1-thread-5:8
pool-1-thread-4:8
pool-1-thread-4:9
pool-1-thread-5:9

Process finished with exit code 0
*/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值