实现线程的三种方式

1.继承Thread类

  • 创建一个继承Thread类的子类
  • 覆写Thread类的run()方法
  • 创建线程类的一个对象
  • 通过线程类的对象调用start()方法启动线程(启动之后会自动调用覆写的run()方法执行线程)
public class ThreadTest extends Thread {        //指定类继承Thread类
    private int count = 10;
    @Override                                   //重写run()方法
    public void run() {
        super.run();
        while(true) {
            System.out.println(count + " ");    //打印count变量
            if(--count == 0) {          //使count变量自减,当自减为0时,退出循环
                break;
            }
        }
    }

    public static void main(String[] args) {
        ThreadTest threadTest = new ThreadTest();//创建线程对象
        threadTest.start();                      //启动线程 
    }

}

2.实现Runnable接口

  • 定义类实现Runnable接口
  • 覆盖Runnable接口中的run()方法(将线程要运行的代码存放在该run()方法中)
  • 通过Thread类建立线程对象
  • 将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数(自定义的run()方法所属的对象是Runnable接口的子类对象,所以要让线程去指定指定对象的run()方法。就必须明确该run()方法所属对象。)
  • 调用Thread类的start()方法开启线程并调用Runnable接口子类的run()方法

这里写图片描述

class Ticket implements Runnable{//定义类Ticket实现Runnable接口
    private int tick = 100;

    @Override           //覆盖Runnable接口中的run()方法
    public void run() {
        while(true) {
            if(tick>0) {
                System.out.println(Thread.currentThread().getName()+"....sale:"+ tick--);
            }
        }
    }

}
public class class03 {

    public static void main(String[] args) {
        Ticket t = new Ticket();        //声明并实例化Runnable子类得到子类对象t
        //通过Thread类建立线程对象,将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);
        //调用Thread类的start()方法开启线程并调用Runnable接口子类的run()方法
        t1.start();
        t2.start();
    }

}

3.通过Callable接口实现多线程
(1)Callable和Runnable的不同

  • Callable规定的方法是call(),而Runnable规定的方法是run().
  • call()方法可抛出异常,而run()方法是不能抛出异常的.
  • Callable的任务执行后可返回值,运行Callable任务可拿到一个Future对象,而Runable的任务是不能返回值的。Future表示异步计算的结果,它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。

(2)优缺点

  • 优点:可以获取返回值,可以对外声明异常
  • 缺点:繁琐

(3)步骤

  • 创建Callable实现类+重写call
  • 借助执行调度服务ExecutorService,获取Future对象。ExecutorService ser = Executors.newFixedThreadPool(2);Future result = ser.submit(实现类对象)
  • 获取值reslt.get()
  • 停止服务ser.shutdownNow()

(4)例子

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

class Race implements Callable<Integer>{

    @Override
    public Integer call() throws Exception {

        return 1000;
    }

}
public class Call {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        //创建线程
        ExecutorService ser = Executors.newFixedThreadPool(1);
        Race tortoise = new Race();
        Future<Integer> result = ser.submit(tortoise);
        //获取值
        int num = result.get();
        System.out.println(num);
        //停止服务
        ser.shutdownNow();
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_40995778/article/details/80076976