面试题:线程

这里写目录标题

Java中的线程和操作系统的线程有什么关系?

线程池提交任务有哪几种方式?分别有什么区别?

  • 提交任务有两种方式:
    • java.util.concurrent.ExecutorService#submit(java.util.concurrent.Callable)
    • java.util.concurrent.Executor#execute(Runnable command);

submit() 与 execute()的区别

  • execute尽可以提交Runnable类型的任务
  • submit既可以提交Runnable类型的任务,也可以提交Callable类型的任务,会有一个类型为Future的返回值,但当任务类型为Runnable时,返回值为null。

调用start()方法和直接调用run()方法的区别?

start()方法实现中,调用了一个关键方法 “private native void start0()”, 本质是调用了JVM的原生函数来启动线程。

run() 方法仅是一个普通的方法

	// 源码
	public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

        /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
        group.add(this);

        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }

    private native void start0();
上一篇:多线程的创建


下一篇:Android自定义线程池——转载