Java - 开启新线程的常见方式

in TCEHJava with 0 comment

继承Thread

public class MainClass {
    public static void main(String[] args) {
        System.out.println("当前线程名:" + Thread.currentThread().getName());
        TestThread thread = new TestThread();
        thread.start();
    }

}

class TestThread extends Thread {
    @Override
    public void run() {
        // super.run();
        System.out.println("当前线程名:" + Thread.currentThread().getName());
    }
}

注:千万不要调用run方法,如果调用run方法好比是对象调用方法,依然还是只有一个主线程,并没有开启新的线程.

实现Runnable接口

    public class MainClass implements Runnable {
    public static void main(String[] args) {
        System.out.println("当前线程名:" + Thread.currentThread().getName());
        Thread thread = new Thread(new MainClass());
        thread.start();
    }
    @Override
    public void run() {
        System.out.println("当前线程名:" + Thread.currentThread().getName());
    }
   }

直接在函数体使用(匿名内部类,其实也是属于第二种实现方式的特例。)

    public class MainClass {
    public static void main(String[] args) {
        System.out.println("当前线程名:" + Thread.currentThread().getName());
        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println("当前线程名:" + Thread.currentThread().getName());
            }
        });
        thread.start();
    }
     }

除此之外,还可以用线程池的方式创建新线程-->java.util.concurrent.Executors

Comments are closed.