Day01 多线程-创建线程的两种方式

方式一:继承thread类

继承thread类,重写run()方法,调用start开启线程 

package Thread;

import java.sql.SQLOutput;

public class TestThread1 extends Thread{
    //创建线程方式一
    public void run(){
        for (int i = 0; i < 200; i++) {
            System.out.println("看代码ing..."+i);
        }
    }

    public static void main(String[] args) {
        //主线程
        //创建一个线程对象
        TestThread1 testThread1=new TestThread1();
         //调用Thread类的start()方法,start()开启线程
        testThread1.start();
        for (int i = 0; i < 1000; i++) {
            System.out.println("我在学多线程..."+i);
        }

    }
}
/**
 * 可以从运行结果看出两个for循环同时进行的
 */

运行结果:

方式二:实现runnable接口

 实现runnable接口,重写run()方法,执行线程需丢入runnable接口实现类,调用start方法

package Thread;
public class TestThread3 implements Runnable {
    //实现runnable接口
    public void run(){
        //run() 方法线程体执行
        for (int i = 0; i < 200; i++) {
            System.out.println("看代码ing"+i);
        }
    }
    public static void main(String[] args) {
        //创建runnable接口的实现类对象
        TestThread3 testThread3=new TestThread3();
        new Thread(testThread3).start(); //Thread(testThread3)实现runnable接口,调用start()方法
        for (int i = 0; i < 1000; i++) {
            System.out.println("多线程..."+i);
        }
    }
}

运行结果:

猜你喜欢

转载自blog.csdn.net/m0_67042480/article/details/129074126