一、 线程启动的方式
Thread类源码注释中截取部分如下
* There are two ways to create a new thread of execution. One is to
* declare a class to be a subclass of <code>Thread</code>. This
* subclass should override the <code>run</code> method of class
* <code>Thread</code>. An instance of the subclass can then be
* allocated and started. For example, a thread that computes primes
* larger than a stated value could be written as follows:
* <hr><blockquote><pre>
* class PrimeThread extends Thread {
* long minPrime;
* PrimeThread(long minPrime) {
* this.minPrime = minPrime;
* }
*
* public void run() {
* // compute primes larger than minPrime
* . . .
* }
* }
* </pre></blockquote><hr>
* <p>
* The following code would then create a thread and start it running:
* <blockquote><pre>
* PrimeThread p = new PrimeThread(143);
* p.start();
* </pre></blockquote>
* <p>
* The other way to create a thread is to declare a class that
* implements the <code>Runnable</code> interface. That class then
* implements the <code>run</code> method. An instance of the class can
* then be allocated, passed as an argument when creating
* <code>Thread</code>, and started. The same example in this other
* style looks like the following:
* <hr><blockquote><pre>
* class PrimeRun implements Runnable {
* long minPrime;
* PrimeRun(long minPrime) {
* this.minPrime = minPrime;
* }
*
* public void run() {
* // compute primes larger than minPrime
* . . .
* }
* }
* </pre></blockquote><hr>
* <p>
* The following code would then create a thread and start it running:
* <blockquote><pre>
* PrimeRun p = new PrimeRun(143);
* new Thread(p).start();
* </pre></blockquote>
注释中说明新启线程有两种方式:
- 继承Thread类
- 实现Runnable接口
代码如下:
public class StartThread {
private static class UseThread extends Thread{
@Override
public void run() {
System.out.println("继承Thread启动线程");
}
}
private static class UseRunnable implements Runnable{
public void run() {
System.out.println("实现Runnable接口新启线程");
}
}
@Test
public void testUseThread(){
UseThread useThread = new UseThread();
useThread.start();
}
@Test
public void testUseRunnable(){
UseRunnable useRunnable = new UseRunnable();
Thread thread = new Thread(useRunnable);
thread.start();
}
}
二、 Thread与Runnable的区别
Thread是对线程的抽象,Runnable是对业务逻辑的抽象
三、 start()与run()的区别
start():让线程进入就绪队列等待分配CPU,分配到CPU才会执行run(),start()方法不能重复被调用,重复调用会抛出异常
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();
run():是业务逻辑实现的地方,本质上和任意一个类的任意成员方法没有任何区别
四、 Callable
一般也有说Java中新启线程还有第三种方式,就是通过Callable使用来达到使用多线程的目的。Callable是JUC包下面的一个接口,只声明了一个方法call(),这是一个泛型接口,方法返回的类型就是传递进来的V类型