java多线程 继承Thread类

编写代码

package com.xiang.lesson01;
//线程开启不一定立即执行,由cpu 高度执行

//创建方式一,继承Thread类,重写run方法,调用start开启线程
public class TestThread1  extends  Thread{
    @Override
    public void run() {
//        run 方法 线程体
        for (int i = 0; i < 5; i++) {
            System.out.println("线程-------------- "+i);
        }
    }

    public static void main(String[] args) {
//        创建一个线程对象
        TestThread1 thread1 = new TestThread1();
//        调用start() 方法开启线程
        thread1.run();
        thread1.start();
//main 线程 ;主线程
        for (int i = 0; i < 10; i++) {
            System.out.println("多线程---------"+i);
        }
    }
}

//交替执行;

运行结果

线程-------------- 0
线程-------------- 1
线程-------------- 2
线程-------------- 3
线程-------------- 4
多线程---------0
多线程---------1
多线程---------2
多线程---------3
多线程---------4
多线程---------5
多线程---------6
多线程---------7
多线程---------8
多线程---------9
线程-------------- 0
线程-------------- 1
线程-------------- 2
线程-------------- 3
线程-------------- 4
posted @ 2021-09-05 17:00  阿向向  阅读(59)  评论(0编辑  收藏  举报