随笔 - 11  文章 - 0 评论 - 0 阅读 - 1196
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

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;
  }
}

posted on   防守三巨臀  阅读(33)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示