Java怎么实现多线程

   2025-02-15 4210
核心提示:Java可以通过实现Thread类或者实现Runnable接口来实现多线程。继承Thread类:public class MyThread extends Thread {public voi

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

继承Thread类:
public class MyThread extends Thread {    public void run() {        // 该方法中的代码会在创建线程后被执行        System.out.println("线程执行了");    }    public static void main(String[] args) {        MyThread thread = new MyThread();        thread.start(); // 启动线程    }}
实现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方法。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言