跳到主要内容

二、创建线程+查看线程+Thread方法+线程状态

一、创建线程的五种方法

前置知识

> 1. Thread 类是用于创建和操作线程的类。每个线程都必须通过 Thread 类的构造方法创建,并实现 run() 方法来执行线程的任务。 > 2. run() 方法是 Thread 类中用于定义线程要执行的任务的方法。当一个线程被启动后,它会调用自己的 run() 方法,在该方法中执行线程的任务逻辑。 > 3. 需要注意的是,直接调用 run() 方法并不会启动一个新的线程,而只会在当前线程中依次执行 run() 方法中的代码。如果要启动一个新的线程并执行 run() 方法中的代码,应该使用 start() 方法来启动线程。

1、方法一:使用继承Thread类,重写run方法

class MyThread extends Thread {

//run是线程的入口方法
@Override
public void run() {

System.out.println("Hello t");
}
}

public class ThreadDemo1 {

//这种方式是使用Thread 的run来描述线程入口
public static void main(String[] args) throws InterruptedException {

// Thread通过接收重写Thread内部run方法的子类
Thread t = new MyThread();
// start 启动线程
t.start();
}
}

2、方法二:实现Runnable接口,重写run方法

在Java中,Runnable是一个函数式接口(Functional Interface),用于表示要在一个线程中执行的任务。

class MyRunnable implements Runnable {

@Override
public void run() {

System.out.println("hello t");
}
}

public class ThreadDemo2 {

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

// 1.先实例化实现了Runnable接口的类
MyRunnable runnable = new MyRunnable();
// 2.通过Thread的构造方法,传入runnable任务,创建线程
Thread t = new Thread(runnable);

t.start();
}
}