Java怎么实现多线程

33次阅读
没有评论

共计 562 个字符,预计需要花费 2 分钟才能阅读完成。

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 方法。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-13发表,共计562字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)