温馨提示×

java中怎么用过thread类创建线程

小亿
96
2024-02-28 11:01:07
栏目: 编程语言

在Java中使用Thread类创建线程可以通过以下步骤实现:

  1. 创建一个类并继承Thread类,重写run()方法,在run()方法中编写线程的执行逻辑。
public class MyThread extends Thread { @Override public void run() { // 线程执行逻辑 System.out.println("Hello, I am a thread!"); } } 
  1. 在主程序中创建线程对象,并调用start()方法启动线程。
public class Main { public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.start(); } } 

通过以上步骤,就可以使用Thread类创建线程并执行线程逻辑。需要注意的是,线程对象只能调用一次start()方法启动线程,如果再次调用会抛出IllegalThreadStateException异常。

0