java线程的创建方式

在Java中,新建线程的方法有两种:

1. 继承`Thread`类并重写`run()`方法

复制代码
class MyThread extends Thread {
@Override
public void run() {
// 在这里编写线程要执行的任务
}
}

public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start(); // 启动线程
}
}
复制代码

2. 实现`Runnable`接口并实现`run()`方法

复制代码
class MyRunnable implements Runnable {
@Override
public void run() {
// 在这里编写线程要执行的任务
}
}

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

 

posted @   HexThinking  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示