Java启动线程的三种方式

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_32099833/article/details/102729662

Thread

继承自Thread。

public class ThreadDemo extends Thread {
	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName() + "-启动了...");
	}

	public static void main(String[] args) {
		ThreadDemo thread = new ThreadDemo();
		thread.start();
		System.out.println(Thread.currentThread().getName() + "-启动了...");
	}
}
输出:
main-启动了...
Thread-0-启动了...

缺点:Java只能单继承,程序不好扩展。

Runnable

实现自Runnable。

public class RunnableDemo implements Runnable {
	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName() + "-启动了...");
	}

	public static void main(String[] args) {
		Runnable runnable = new RunnableDemo();
		new Thread(runnable).start();
		System.out.println(Thread.currentThread().getName() + "-启动了...");
	}
}
输出:
main-启动了...
Thread-0-启动了...

Java可以多实现,解决了 Thread 不好扩展的问题,推荐使用。

Callable

支持返回值。

public class CallableDemo implements Callable<String> {
	@Override
	public String call() throws Exception {
		System.out.println(Thread.currentThread().getName()+"-启动了...");
		Thread.sleep(3000);
		return "Lisa";
	}

	public static void main(String[] args) throws Exception {
		Callable callable = new CallableDemo();
		FutureTask<String> task = new FutureTask(callable);
		Thread thread = new Thread(task);
		thread.start();
		// get()方法会阻塞
		String result = task.get();
		System.out.println(result);
		System.out.println(Thread.currentThread().getName()+"-运行结束.");
	}
}
输出:
Thread-0-启动了...
Lisa
main-运行结束.

get源码

通过FutureTask的get()源码可以看一下具体实现。

/**
 * @throws CancellationException {@inheritDoc}
 */
public V get() throws InterruptedException, ExecutionException {
    int s = state;
    if (s <= COMPLETING)
        s = awaitDone(false, 0L);
    return report(s);
}

重点是 awaitDone

private int awaitDone(boolean timed, long nanos)
    throws InterruptedException {
    final long deadline = timed ? System.nanoTime() + nanos : 0L;
    WaitNode q = null;
    boolean queued = false;
    for (;;) {
        if (Thread.interrupted()) {
            removeWaiter(q);
            throw new InterruptedException();
        }

        int s = state;
        if (s > COMPLETING) {
            if (q != null)
                q.thread = null;
            return s;
        }
        else if (s == COMPLETING) // cannot time out yet
            Thread.yield();
        else if (q == null)
            q = new WaitNode();
        else if (!queued)
            queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                 q.next = waiters, q);
        else if (timed) {
            nanos = deadline - System.nanoTime();
            if (nanos <= 0L) {
                removeWaiter(q);
                return state;
            }
            LockSupport.parkNanos(this, nanos);
        }
        else
            LockSupport.park(this);
    }
}

通过一个 for ( ; ; ) 死循环监听线程状态,线程运行完毕才返回结果值。

猜你喜欢

转载自blog.csdn.net/qq_32099833/article/details/102729662
今日推荐