Thread基础-创建线程的方式

Java线程创建的几种简单方式

1. extends Thread类


public class ThreadDemo extends Thread{

    @Override
    public void run() {
        System.out.println("this is a Thread class run method.");
    }

}

2. implements Runnable接口

public class RunnableDemo implements Runnable{

    @Override
    public void run() {
        System.out.println("this is a runnable interface.");
    }

}

提个小问题:如果继承了Thread类重写了run方法又实现了Runnable接口,那么执行的是那个run方法呢?

public class MyRunnable implements Runnable{

    @Override
    public void run() {
        System.out.println("runnable method");
    }
    
    /* main() */
    public static void main(String[] args) {
        MyRunnable mr = new MyRunnable();
        new Thread(mr) {
            @Override
            public void run() {
                System.out.println("Thread method");
            }
        }.start();
    }

}

输出结果为:Thread method

Thread中的run方法代码为

    /* What will be run. */
    private Runnable target;

    /**
     * If this thread was constructed using a separate
     * <code>Runnable</code> run object, then that
     * <code>Runnable</code> object's <code>run</code> method is called;
     * otherwise, this method does nothing and returns.
     * <p>
     * Subclasses of <code>Thread</code> should override this method.
     *
     * @see     #start()
     * @see     #stop()
     * @see     #Thread(ThreadGroup, Runnable, String)
     */
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

传入Thread的Runnable会被保存为"target"对象,调用时会通过Thread中的run方法判断执行,但是在上面的代码中重写了Thread.run方法。所以结果很明显...

3. 线程池创建线程

    public static void main(String[] args) {
        ExecutorService es = Executors.newFixedThreadPool(3);
        // 
        for (int i = 0; i < 10; i++) {
            es.execute(() -> {
                System.out.println(Thread.currentThread().getName());
            });
        }
    }

4. FuterTask & Callable 可获取线程执行结果

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;


public class MyCallable implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        int v = 0;
        int random = new Random().nextInt(200);
        System.out.println("random num:" + random);
        for (int i = 0; i < random; i++) {
            System.out.println(Thread.currentThread().getName() + "----" + i);
            v += i;
        }
        return v;
    }

    public static void main(String[] args) {
        MyCallable mc = new MyCallable();
        FutureTask<Integer> ft = new FutureTask<Integer>(mc);
        for (int i = 0; i < 20; i++) {
            new Thread(ft, "tn--" + i).start();
        }
        // get result
        try {
            Integer result = ft.get();
            System.out.println(result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
posted @ 2020-04-14 19:45  thinkMIne  阅读(169)  评论(0)    收藏  举报
/*粒子线条,鼠标移动会以鼠标为中心吸附的特效*/