Thread、Runnable、Callable三种创建线程的简单示例及区别简介

来源:互联网 发布:单片机地址寄存器 编辑:程序博客网 时间:2024/06/06 02:38

一、继承Thread类
1、编写线程类,继承Thread类
2、重写run()方法
把该线程需要完成的任务代码写在run()中,也称为线程体
3、创建线程类的对象
4、启动线程,必须调用从Thread类继承过来的start()

示例:

public class TestThread extends Thread{    @Override    public void run() {        super.run();        for(int i = 0;i<1000;i++){            System.out.println("TestThread执行了");        }    }    public static void main(String[] args) {        TestThread tt = new TestThread();        tt.start();        for (int i = 0; i < 1000; i++) {            System.out.println("main执行了");        }    }}

二、实现Runnable接口
1、编写线程类,实现Runnable接口
2、实现run()方法
把该线程需要完成的任务代码写在run()中
3、创建线程类的对象
4、启动线程,通过Thread类的代理对象,调用start()方法来启动线程

示例:

public class TestRunnable implements Runnable {    @Override    public void run() {        for(int i=0;i<1000;i++){            System.out.println("TestRunnable被执行了");        }    }    public static void main(String[] args) {        TestRunnable tr = new TestRunnable();        Thread thread = new Thread(tr);        thread.start();        for(int i=0;i<1000;i++){            System.out.println("主线程被执行了");        }    }}

继承Thread类与实现Runnable接口的区别
1、启动线程的方式不同
2、继承Thread类受到单继承的限制,而实现Runnable接口没有这个限制
3、如果多个线程需要使用共享数据时,继承Thread类的方式,需要使用static解决,而实现Runnable接口的方式,只要共用Runnable的实现类对象即可
4、如果要解决线程安全问题,继承Thread类,只能选择static的锁或类名.class当锁,而实现Runnable接口的可以使用this

三、实现Callable接口
1、编写线程类,实现Callable接口,指定线程执行结果的返回类型
2、实现call()方法,
把该线程需要完成的任务代码写在call()中(抛出异常类型可指定)
3、创建线程类的对象
将线程类对象放进FutureTask的对象中
4、启动线程,通过Thread类的代理对象,调用start()方法来启动线程
示例:

import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.FutureTask;public class TestCallable implements Callable<Integer> {    @Override    public Integer call() throws Exception {        int sum = 0;        for(int i=0;i<1000;i++){            System.out.println("TestCallable被调用了"+i+"次");            sum +=i;        }        return sum;    }    public static void main(String[] args) {        TestCallable tc = new TestCallable();        FutureTask<Integer> future = new FutureTask<Integer>(tc);        new Thread(future).start();        for(int i=0;i<1000;i++){            System.out.println("主线程被执行了"+i+"次");        }        try {            //result用于接收线程new Thread(future).start()执行结果            Integer result = future.get();            System.out.println(result);        } catch (InterruptedException | ExecutionException e) {            e.printStackTrace();        }    }}

实现Callable接口方式的特点:
1、相较于其他两种方式,方法可以有返回值,并且可以抛出异常
2、实现Callable接口方式,需要FutureTasksh实现类的支持,用于接收运算结果。

阅读全文
0 0