java多线程的 实现有两种方式:一,继承Runnable接口,实现run()方法;二 ,继承Thread类,重写run()方法。使用线程时将 逻辑写在run方法中 ,当 线程 启动(Thread.start())后,分配 到CPU资源就会执行其中的逻辑。
查看Thread类的 源码即可发现,Thread类也是实现 了Runnable接口。而Runnable接口只有一个抽象方法
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
多线程中 我们实现的run()方法只是一个 普通方法,我们想要使多线程执行需要 用 Thread类提供的start()方法
public synchronized void start() {
if (threadStatus != 0)
throw new IllegalThreadStateException();
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 */
}
}
}
查看 源代码,我们可以看到start()方法是调用了 start0()这个 方法 ,而这个 方法我们可以看到
private native void start0();
只有一行,但是 是使用native这个关键字修修饰的,我想我们最早 接触这个关键字最有 可能的就是 在这 了,这个 关键字标志调用本地系统的方法 ,也就是交给你 的 操作系统 去执行线程。
由于线程的创建 方式的 不同,我们在启动 线程的时候也有一点差别,对于 继承Thread类的线程 来说 ,父类(Thread)提供了 很多方法,其中就有start()方法 ,所以我们可以 通过实例去直接调用start方法 来启动线程。而继承Runnable接口实现 run方法的 线程有些许不同,Runnable接口只提供 了run方法 ,其他的 所有方法 我们都是 没有的,而且我们自己自己写 的 start()方法是不能使用的,会抛出
java.lang.UnsatisfiedLinkError
这个异常。幸好Thread类已经提供 了解决方案 ,Thread类有很多构造方法,我们创建Thread类的实例,将 我们自己写好 的线程传进去,再通过Thread类的实例 即可调用Thread类的所以 方法操作线程 。