Java - 多线程

基本概念

线程: 线程是操作系统能够进行运算调度的最下单位。它被包含在进程之中,是进程中的实际运作单位
进程: 进程是程序的基本执行实体。

并发: 在同一时刻,有多个指令在单个CPU上交替执行。
并行: 在同一时刻,有多个指令在多个CPU上同时执行。

实现多线程

方式1: 继承Thread类

package com.threaddemo;

public class MyThread  extends  Thread{

    @Override
    public void run(){
        for (int i = 0; i < 100; i++) {
            System.out.println(getName() + "hello word");
        }
    }

}

启动线程:

    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();

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

    }

方式2:实现Runable接口

package com.threaddemo;

public class MyRun implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + "hello world");
        }
    }
}

启动线程:

        MyRun r1 = new MyRun();
        MyRun r2 = new MyRun();

        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);

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

方式3:
特点:可以获取到多线程运行结果

  1. 创建一个类MyCallable 实现 Callable 接口
  2. 重写call (是有返回值的,表示多线程运行的结果)
  3. 创建MyCallable的对象(表示多线程要执行的任务)
  4. 创建FutuerTask对象(管理多线程运行的结果)
  5. 创建Thread类的对象,并启动(表示线程)
package com.threaddemo;

import java.util.concurrent.Callable;

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

启动线程并获取线程执行结果:

MyCallable myCallable = new MyCallable();
FutureTask<Integer> ft = new FutureTask<>(myCallable);
Thread thread = new Thread(ft);
thread.start();
Integer result = ft.get();
System.out.println(result);

image

Thread 常见成员方法

image

守护线程

细节: 当其他的非守护线程执行完毕之后,守护线程会陆续结束
通俗易懂:当女神线程结束了,那么备胎也没有存在的必要了

package com.threaddemo;

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


package com.threaddemo;

public class MyThread2 extends Thread{

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

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

        MyThread1 t1 = new MyThread1();
        MyThread2 t2 = new MyThread2();

        t1.setName("女神线程");
        t2.setName("备胎线程");

        t2.setDaemon(true);

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

image

线程的生命周期

image

同步代码块

细节:

  1. 锁对象一定要是唯一的,一般是当天类的字节码对象
posted @ 2026-02-19 15:03  chuangzhou  阅读(11)  评论(0)    收藏  举报