Java使用Thread类代表线程,所有的线程对象都必须是Thread类或其子类的实例。Java可以用四种方式来创建线程:
继承Thread创建线程
实现Runnable接口创建线程
实现callable接口实现线程
使用线程池Executor创建线程
1.继承Thread实现线程
我们先来看一下Thread的源码,它是一个类,同样也实现了Runnable接口
public
class Thread implementsRunnable {/*Make sure registerNatives is the first thing does.*/
private static native voidregisterNatives();static{
registerNatives();
}private volatileString name;private intpriority;privateThread threadQ;private longeetop;/*Whether or not to single_step this thread.*/
private booleansingle_step;/*Whether or not the thread is a daemon thread.*/
private boolean daemon = false;/*JVM state*/
private boolean stillborn = false;/*What will be run.*/
privateRunnable target;/*The group of this thread*/
privateThreadGroup group;/*The context ClassLoader for this thread*/
privateClassLoader contextClassLoader;/*The inherited AccessControlContext of this thread*/
privateAccessControlContext inheritedAccessControlContext;/*For autonumbering anonymous threads.*/
private static intthreadInitNumber;private static synchronized intnextThreadNum() {return threadInitNumber++;
}/*ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class.*/ThreadLocal.ThreadLocalMap threadLocals= null;/** InheritableThreadLocal values pertaining to this thread. This map is
* maintained by the InheritableThreadLocal class.*/ThreadLocal.ThreadLocalMap inheritableThreadLocals= null;/** The requested stack size for this thread, or 0 if the creator did
* not specify a stack size. It is up to the VM to do whatever it
* likes with this number; some VMs will ignore it.*/
private longstackSize;/** JVM-private state that persists after native thread termination.*/
private longnativeParkEventPointer;/** Thread ID*/
private longtid;/*For generating thread ID*/
private static longthreadSeqNumber;/*Java thread status for tools,
* initialized to indicate thread 'not yet started'*/
private volatile int threadStatus = 0;//......
}
通过继承Thread类来创建并启动多线程的一般步骤如下
1】d定义Thread类的子类,并重写该类的run()方法,该方法的方法体就是线程需要完成的任务,run()方法也称为线程执行体。
2】创建Thread子类的实例,也就是创建了线程对象
3】启动线程,即调用线程的start()方法
代码示例:
public classThreadTest {public static voidmain(String[] args) {newMyThread().start();
}static class MyThread extends Thread {//继承Thread
public voidrun() {
System.out.println("我是继承Thread类!! ");
}
}
}
2.实现Runnable接口创建线程
我们来看一下Runnable的源码,它是一个接口:
@FunctionalInterfacepublic interfaceRunnable {/*** When an object implementing interface Runnable
is used
* to create a thread, starting the thread causes the object's
* run
method to be called in that separately executing
* thread.
*
* The general contract of the method run
is that it may
* take any action whatsoever.
*
*@seejava.lang.Thread#run()*/
public abstract voidrun();
}
由于run()方法返回值为void类型,所以在执行完任务之后无法返回任何结果。
通过实现Runnable接口创建并启动线程一般步骤如下:
1】定义Runnable接口的实现类,一样要重写run()方法,这个run()方