多线程的三种实现方式

发布时间 2023-12-14 21:11:02作者: 防守三巨臀

1.什么是多线程

有了多线程就可以让程序同时进行多件事情。

2.多线程的作用

提高效率

3.应用场景

只要是想多件事情同时运行就需要用到多线程。

4.并发和并行

并发:在同一时刻,有多个指令在单个cpu上交替运行
并行:在同一时刻,有多个指令在多个cpu上同时运行
并发和并行有可能同时发生

三种实现线程的方式

1.继承 Thread

public class ThreadDemo {
public static void main(String[] args) {
  /*
  * 多线程的第一种启动方式:
  * 1. 自己定义一个类继承Thread
  * 2. 重写run方法
  * 3. 创建子类的对象,并启动线程
  * */
  MyThread t1 = new MyThread();
  MyThread t2 = new MyThread();

  t1.setName("线程1");
  t2.setName("线程2");

  t1.start();
  t2.start();
  }
}

public class MyThread extends Thread{

  @Override
  public void run() {
  //书写线程要执行代码
  for (int i = 0; i < 100; i++) {
  System.out.println(getName() + "HelloWorld");
  }
  }
}

2.实现Runnable接口

public class ThreadDemo {
  public static void main(String[] args) {
    /*
    * 多线程的第二种启动方式:
    * 1.自己定义一个类实现Runnable接口
    * 2.重写里面的run方法
    * 3.创建自己的类的对象
    * 4.创建一个Thread类的对象,并开启线程
    * */


    //创建MyRun的对象
    //表示多线程要执行的任务
    MyRun mr = new MyRun();

    //创建线程对象
    Thread t1 = new Thread(mr);
    Thread t2 = new Thread(mr);

    //给线程设置名字
    t1.setName("线程1");
    t2.setName("线程2");

    //开启线程
    t1.start();
    t2.start();
  }
}

 

public class MyRun implements Runnable{

  @Override
  public void run() {
  //书写线程要执行的代码
  for (int i = 0; i < 100; i++) {
  //获取到当前线程的对象
  /*Thread t = Thread.currentThread();

  System.out.println(t.getName() + "HelloWorld!");*/
  System.out.println(Thread.currentThread().getName() + "HelloWorld!");
  }
  }
}

3.实现Callable接口

public class ThreadDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {

    /*
    * 多线程的第三种实现方式:
    * 特点:可以获取到多线程运行的结果
    *
    * 1. 创建一个类MyCallable实现Callable接口
    * 2. 重写call (是有返回值的,表示多线程运行的结果)
    *
    * 3. 创建MyCallable的对象(表示多线程要执行的任务)
    * 4. 创建FutureTask的对象(作用管理多线程运行的结果)
    * 5. 创建Thread类的对象,并启动(表示线程)
    * */

    //创建MyCallable的对象(表示多线程要执行的任务)
    MyCallable mc = new MyCallable();
    //创建FutureTask的对象(作用管理多线程运行的结果)
    FutureTask<Integer> ft = new FutureTask<>(mc);
    //创建线程的对象
    Thread t1 = new Thread(ft);
    //启动线程
    t1.start();

    //获取多线程运行的结果
    Integer result = ft.get();
    System.out.println(result);

  }
}

 

import java.util.concurrent.Callable;

public class MyCallable implements<Integer> {

    @Override
    public Integer call() throws Exception {
    //求1~100之间的和
    int sum = 0;
    for (int i = 1; i <= 100; i++) {
    sum = sum + i;
    }
    return sum;
  }
}