[多线程-2]. 线程的创建的两种方式

使用Thread的子类

通过继承Thread类和重写run()方法来规定线程的具体操作.

使用Thread类

使用Thread创建线程通常使用的方法:

Thread(Runnable target)

方法参数是一个实现Runnable接口类的实例,称作所创建现场的目标对象.
与Thread类的子类不同的是,当线程调用start()方法后,一旦轮到他使用cpu资源时会自动调用run()方法.

package implement;

public class SayHello implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            System.out.println("hello");
        }
    }
}

package test;

import implement.SayHello;

public class Test_2 {
    public static void main(String[] args) {
        Thread helloThread;
        SayHello sayHello;
        sayHello=new SayHello();
        helloThread=new Thread(sayHello);
        helloThread.start();
    }
}

你可能感兴趣的:([多线程-2]. 线程的创建的两种方式)