基本概念
关于操作系统中线程的概念,可参考另一篇博文:进程与线程
在Java中,线程可以理解为一组指令的集合,或者程序的特殊段,可以独立运行。轻量级进程,负责在单个程序中执行和完成多任务。
多线程是实现多任务(多任务操作系统)的一种方式。可以把耗时长的任务放到后台去处理,减少与用户交互等待时间。
生命周期
- 新建状态(New):当线程对象对创建后,即进入了新建状态,如:Thread t = new MyThread();
- 就绪状态(Runnable):
- 运行状态(Running):当CPU开始调度处于就绪状态的线程时,此时线程才得以真正执行,即进入到运行状态。就绪状态是进入到运行状态的唯一入口。
- 阻塞状态(Blocked):处于运行状态中的线程由于某种原因,暂时放弃对CPU的使用权,停止执行,此时进入阻塞状态,直到其进入到就绪状态,才 有机会再次被CPU调用以进入到运行状态。根据阻塞产生的原因不同,阻塞状态又可以分为三种:等待阻塞【运行状态中的线程执行wait()方法,使本线程进入到等待阻塞状态】;同步阻塞【线程在获取synchronized同步锁失败(因为锁被其它线程所占用),它会进入同步阻塞状态】;其他阻塞【通过调用线程的sleep()或join()或发出了I/O请求时,线程会进入到阻塞状态】
- 死亡状态(Dead):线程执行完了或者因异常退出了run()方法,该线程结束生命周期
创建方法
首先了解线程的继承关系:根接口:Runnable,只含有一个返回为空的抽象方法:public abstract void run();
public interface Runnable {
/**
* When an object implementing interface Runnable is used to create a thread,starting the
* thread causes the object's method to be called in that separately executing thread.
*/
public abstract void run();
}
Thread类:实现了Runnable接口,关键属性:name是表示Thread的名字;priority表示线程的优先级(最大值为10,最小值为1,默认值为5),daemon表示线程是否是守护线程,target表示要执行的任务。
继承Thread类必须重写run方法,在run方法中定义具体要执行的任务。详细介绍:http://www.cnblogs.com/dolphin0520/p/3920357.html
public class Thread implements Runnable {
/* Make sure registerNatives is the first thing <clinit> does. */
private static native void registerNatives();
static {
registerNatives();
}
private char name[];
private int priority;
private Thread threadQ;
private long eetop;
/* Whether or not to single_step this thread. */
private boolean single_step;
/* Whether or not the thread is a daemon thread. */
private boolean daemon = false;
/* JVM state */
private boolean stillborn = false;
/* What will be run. */
private Runnable target;
/* The group of this thread */
private ThreadGroup group;
/* The context ClassLoader for this thread */
private ClassLoader contextClassLoader;
/* The inherited AccessControlContext of this thread */
private AccessControlContext inheritedAccessControlContext;
/* For autonumbering anonymous threads. */
private static int threadInitNumber;
private static synchronized int nextThreadNum() {
return threadInitNumber++;
}
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 */
}
}
}
private native void start0();
1. 继承Thread类,重写run()方法
Thread主要方法:
- sleep():sleep相当于让线程睡眠,交出CPU,让CPU去执行其他的任务。(不会释放锁;必须捕获InterruptedException异常或者将该异常向上层抛出;进入阻塞状态)
- yield():让当前线程交出CPU权限,让CPU去执行其他的线程。(不会释放锁;不能控制具体的交出CPU的时间;不会让线程进入阻塞状态,而是让线程重回就绪状态)
package com.xianggen.thread;
/**
*
* @author xianggen
* @2016年8月24日 下午6:02:35
*/
public class ExtendsThread extends Thread{
private int i=0;
private Object object=new Object();
public static void main(String[] args) {
ExtendsThread myThread1=new ExtendsThread();
ExtendsThread myThread2=new ExtendsThread();
myThread1.start();
myThread2.start();
}
public void run(){
//System.out.println("complete thread by extends Thread!");
synchronized (object) {
i++;
System.out.println("i="+i);
try{
System.out.println("Thread:"+Thread.currentThread().getName()+" begin sleep!");
//调用sleep方法相当于让线程进入阻塞状态。
Thread.currentThread().sleep(5000);
}catch(InterruptedException e){
}
System.out.println("Thread:"+Thread.currentThread().getName()+" sleep over!");
i++;
System.out.println("i="+i);
}
}
}
**2.实现Runnable接口,重写run()方法
创建Runnable实现类的实例,并以此实例作为Thread类的target来创建Thread对象,该Thread对象才是真正的线程对象。见代码:
package com.xianggen.thread;
/**
* 如果类已经extends另一个类,就无法直接extends Thread,
* 此时,必须实现一个Runnable接口
* @author xianggen
* @2016年8月25日 上午10:14:43
*/
public class ExtendsRunnable implements Runnable {
public void run() {
for(int i=0;i<10;i++)
System.out.println(Thread.currentThread().getName()+" "+i);
}
public static void main(String[] args) {
ExtendsRunnable eR=new ExtendsRunnable();
//首先实例化一个Thread,并传入自己的Thread实例
Thread thread=new Thread(eR);
Thread thread2=new Thread(eR);
thread.start();
thread2.start();
}
}
3.使用Callable和Future接口创建线程
特点:使用ExecutorService、Callable、Future实现了有返回结果的多线程,而前两种方法没有返回结果
这一方法平时接触的最少。具体步骤:创建Callable接口的实现类,并实现call()方法【不同于run()方法,call()有返回值】,使用FutureTask类来包装Callable实现类的对象,且以此FutureTask对象作为Thread对象的target来创建线程。
package com.xianggen.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* 有返回值多线程
* @author xianggen
* @2016年8月25日 上午10:52:03
*/
public class AnotherThread implements Callable<Integer> {
private int i = 0;
// 与run()方法不同的是,call()方法具有返回值
public Integer call() {
int sum = 0;
for (; i < 100; i++) {
System.out.println(Thread.currentThread().getName());
sum += i;
}
return sum;
}
public static void main(String[] args) {
//创建AnotherThread对象
Callable<Integer> callable=new AnotherThread();
//使用FutureTask包装thread对象
FutureTask<Integer> ft=new FutureTask<Integer>(callable);
Thread thread=new Thread(ft);
thread.start();
System.out.println("main thread for over!");
try{
int sum=ft.get();//获取call()方法中的返回值!
System.out.println("sum="+sum);
}catch(InterruptedException e){
e.printStackTrace();
}catch(ExecutionException e){
e.printStackTrace();
}
}
}