Java SE 8 API文档: docs.oracle.com/javase/8/do…java
请查看java.lang.Thread的类说明文档。api
官方原话:There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread
. This subclass should override the run
method of class Thread
.oracle
/** * 实现线程的第一个方式 继承Thread * @author yiren */
public class MyThread extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " Thread running...");
}
public static void main(String[] args) throws IOException {
new MyThread().start();
System.in.read();
}
}
复制代码
官方原话:The other way to create a thread is to declare a class that implements the Runnable
interface. That class then implements the run
method.异步
/** * 实现线程的第二个方式 实现Runnable接口 * @author yiren */
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " Runnable running...");
}
public static void main(String[] args) throws IOException {
new Thread(new MyRunnable()).start();
System.in.read();
}
}
复制代码
Thread
,每次想建一个异步任务,咱们都须要去创建一个独立的线程。而建立一个线程的消耗是比较大的,若是是使用Runnable
,咱们就能够很好得利用线程池之类的工具,这样能够大大减小建立和销毁线程的损耗。节省资源。Thread
的类事后,该类就没法再继承其余类,大大限制了可扩展性。/* What will be run. */
private Runnable target;
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
private void init(ThreadGroup g, Runnable target, String name, long stackSize) {
init(g, target, name, stackSize, null, true);
}
private void init(ThreadGroup g, Runnable target, String name, long stackSize, AccessControlContext acc, boolean inheritThreadLocals) {
......
this.target = target;
......
}
@Override
public void run() {
if (target != null) {
target.run();
}
}
复制代码
两种方法的本质(由上面的Thread类的源代码可知)ide
Thread
是整个run()
方法被重写Runnable
最终是Runnable
的run
方法被target.run()
调用若是两种方式都用会有什么效果呢?微服务
/** * @author yiren */
public class MyThreadAndRunnable {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " runnable running...");
}
}
) {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " thread running...");
}
};
// 这个地方应该是执行重写Thread类的run方法中的逻辑!
thread.start();
}
}
复制代码
Thread
的run()
方法就是调用target.run()
,若是重写那也就没有调用target.run()
了。准确来讲,建立线程只有一种方式,那就是构建Thread
类,而实现线程的执行单元有两种方法,就是上面说的两种。工具
线程池建立线程学习
/** * wrong 线程池建立 * * @author yiren */
public class ThreadPoolExample {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 1000; i++) {
executorService.submit(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
});
}
}
}
// Executors中的DefaultThreadFactory
static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
DefaultThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
复制代码
newThread()
方法可知,即便是线程池,本质上仍是使用Thread
的建立线程。Callable和FutureTask建立线程大数据
由上UML图可知,实际上内部仍是使用的Thread和Runnable来实现的。this
定时器Timer
/** * @author yiren */
public class TimerExample {
public static void main(String[] args) {
Timer timer = new Timer();
// 每隔1s打印下本身的名字
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " timer running...");
}
}, 1000, 1000);
}
}
复制代码
TimerTask
这个抽象类匿名内部类、Lambda表达式 (本质也是同样的)
/** * 匿名内部类 * @author yiren */
public class AnonymousInnerClassExample {
public static void main(String[] args) {
new Thread() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}.start();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}).start();
}
}
/** * lambda表达式 * @author yiren */
public class LambdaExample {
public static void main(String[] args) {
new Thread(() -> System.out.println(Thread.currentThread().getName())).start();
}
}
复制代码