温馨提示×

Java怎么实现多线程

小亿
89
2023-11-13 10:47:28
栏目: 编程语言
Java开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

Java可以通过实现Thread类或者实现Runnable接口来实现多线程。

  1. 继承Thread类:
public class MyThread extends Thread {
    public void run() {
        // 该方法中的代码会在创建线程后被执行
        System.out.println("线程执行了");
    }

    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start(); // 启动线程
    }
}
  1. 实现Runnable接口:
public class MyRunnable implements Runnable {
    public void run() {
        // 该方法中的代码会在创建线程后被执行
        System.out.println("线程执行了");
    }

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

以上两种方式都是创建线程,区别在于继承Thread类要直接实现run方法,而实现Runnable接口要通过传入Runnable对象来创建Thread对象,并在Runnable对象中实现run方法。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:Java多线程如何实现线程通信

0