温馨提示×

怎么在java中实现线程

小亿
83
2024-01-09 23:32:16
栏目: 编程语言

在Java中,可以通过以下两种方式来实现线程:

  1. 继承Thread类:
public class MyThread extends Thread {
    @Override
    public void run() {
        // 线程执行的代码
        System.out.println("线程运行中");
    }

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start(); // 启动线程
    }
}
  1. 实现Runnable接口:
public class MyRunnable implements Runnable {
    @Override
    public void run() {
        // 线程执行的代码
        System.out.println("线程运行中");
    }

    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start(); // 启动线程
    }
}

无论是继承Thread类还是实现Runnable接口,都需要重写run()方法,该方法中定义线程要执行的代码。然后通过创建线程对象,并调用start()方法来启动线程。

0