java线程 Thread

package com.tedu.threadStudy;

public class studyThread {
    public static void main(String[] args) {
        MyThread th1 = new MyThread("线程1");
        MyThread th2 = new MyThread("线程2");
        th1.start();
        th2.start();

    }
}
class MyThread extends Thread{
    private final String name;

    public MyThread(String name){
        this.name = name;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(name+"线程执行了");

        }
    }
}

通过继承接口的方式实现多线程

package com.tedu.threadStudy;

public class studyRunnable {
    public static void main(String[] args) {
        MyThread2 th1 = new MyThread2("线程一");
        MyThread2 th2 = new MyThread2("线程二");
        // 通过接口实现,必须通过类重新实例化
        Thread tha = new Thread(th1, "1");
        Thread thb = new Thread(th2, "2");
        tha.start();
        thb.start();

    }
}
class MyThread2 implements Runnable{
    private String name;
    public MyThread2(String name){
        this.name = name;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(name+"线程执行了");
        }
    }
}
posted @   竹石2020  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示