Java并发 —— 线程的创建

Java并发 —— 线程的创建_第1张图片

我们当中的绝大多数人,在人到中年之后,都很难活成个清风朗日、挥斥方遒的洒脱模样,更多时候面临的是平凡琐屑的一生。


线程状态:
图片来源
Java并发 —— 线程的创建_第2张图片
线程状态有:new, ready, running, waiting, terminated, blocked

1.使用Runnable 接口

Runnable 源码

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface Runnable is used
     * to create a thread, starting the thread causes the object's
     * run method to be called in that separately executing
     * thread.
     * 

* The general contract of the method run is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public abstract void run(); }

Runnable 接口中仅有一个run()抽象函数

通过接口Runnable 实现多线程

class Solution {

    public static class RunableTask implements Runnable{

        @Override
        public void run(){
            System.out.println(Thread.currentThread());
        }
    }
    public static void main(String[] args) {
        RunableTask runableTask = new RunableTask();

        new Thread(runableTask).start();
        new Thread(runableTask).start();
    }
}

输出结果:
Java并发 —— 线程的创建_第3张图片

可以看到,实现了Runnable 接口的类被送到了Thread()中进行启动线程

Java并发 —— 线程的创建_第4张图片
Thread类也继承了Runnable 接口,通过new Thread(runnable),使用构造函数创建新线程。

 /**
     * Allocates a new {@code Thread} object. This constructor has the same
     * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
     * {@code (null, target, gname)}, where {@code gname} is a newly generated
     * name. Automatically generated names are of the form
     * {@code "Thread-"+}n, where n is an integer.
     *
     * @param  target
     *         the object whose {@code run} method is invoked when this thread
     *         is started. If {@code null}, this classes {@code run} method does
     *         nothing.
     */
    public Thread(Runnable target) {
        init(null, target, "Thread-" + nextThreadNum(), 0);
    }
    
    /**
     * Initializes a Thread with the current AccessControlContext.
     * @see #init(ThreadGroup,Runnable,String,long,AccessControlContext,boolean)
     */
    private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize) {
        init(g, target, name, stackSize, null, true);
    }
/**
     * Initializes a Thread.
     *
     * @param g the Thread group
     * @param target the object whose run() method gets called
     * @param name the name of the new Thread
     * @param stackSize the desired stack size for the new thread, or
     *        zero to indicate that this parameter is to be ignored.
     * @param acc the AccessControlContext to inherit, or
     *            AccessController.getContext() if null
     * @param inheritThreadLocals if {@code true}, inherit initial values for
     *            inheritable thread-locals from the constructing thread
     */
    private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc,
                      boolean inheritThreadLocals) {
        if (name == null) {
            throw new NullPointerException("name cannot be null");
        }

        this.name = name;
        ............... //代码过长,就不贴了

2.继承extend

重写Thread类的run()方法,调用Threadstart()即可启动线程

class Solution {

    public static class MyThread extends Thread{

        @Override
        public void run(){
            System.out.println(Thread.currentThread());
        }
    }
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}

3.FutureTask 线程返回值

创建CallerTask 任务类,将该任务传递给Thread 并启动线程,之后便可以将返回值通过get()方法获取。

class Solution {

    public static class CallerTask implements Callable<String>{

        @Override
        public String call() throws Exception{
            return Thread.currentThread().toString();
        }
    }
    public static void main(String[] args) throws Exception {
        FutureTask<String> futureTask = new FutureTask<>(new CallerTask());

        new Thread(futureTask).start();

        String res = futureTask.get();
        System.out.println(res);
    }
}

你可能感兴趣的:(Java)