Thread线程相关
1.线程生命周期
Thread类中定义的线程枚举状态:
- NEW:线程刚刚创建,但没有开始执行start
- RUNNABLE:线程所需运行的资源均已准备完成
- BLOCKED:线程执行时遇到同步块时,进入阻塞状态,直到获取到请求的锁信息
- WAITING:进入无时间限制的等待状态
- TIMED.WAITING:进入有限时间的等待状态
- TERMINATED:线程执行结束。
public enum State {
/**
* Thread state for a thread which has not yet started.
*/
NEW,
/**
* Thread state for a runnable thread. A thread in the runnable
* state is executing in the Java virtual machine but it may
* be waiting for other resources from the operating system
* such as processor.
*/
RUNNABLE,
/**
* Thread state for a thread blocked waiting for a monitor lock.
* A thread in the blocked state is waiting for a monitor lock
* to enter a synchronized block/method or
* reenter a synchronized block/method after calling
* {@link Object#wait() Object.wait}.
*/
BLOCKED,
/**
* Thread state for a waiting thread.
* A thread is in the waiting state due to calling one of the
* following methods:
* <ul>
* <li>{@link Object#wait() Object.wait} with no timeout</li>
* <li>{@link #join() Thread.join} with no timeout</li>
* <li>{@link LockSupport#park() LockSupport.park}</li>
* </ul>
*
* <p>A thread in the waiting state is waiting for another thread to
* perform a particular action.
*
* For example, a thread that has called <tt>Object.wait()</tt>
* on an object is waiting for another thread to call
* <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
* that object. A thread that has called <tt>Thread.join()</tt>
* is waiting for a specified thread to terminate.
*/
WAITING,
/**
* Thread state for a waiting thread with a specified waiting time.
* A thread is in the timed waiting state due to calling one of
* the following methods with a specified positive waiting time:
* <ul>
* <li>{@link #sleep Thread.sleep}</li>
* <li>{@link Object#wait(long) Object.wait} with timeout</li>
* <li>{@link #join(long) Thread.join} with timeout</li>
* <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
* <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
* </ul>
*/
TIMED_WAITING,
/**
* Thread state for a terminated thread.
* The thread has completed execution.
*/
TERMINATED;
}
2.线程基本操作
2.1新建线程
继承Thread类实现:
/**
* 继承Thread类,Thread类的实现是实现Runnable接口
* @author wsz
* @date 2017年11月26日
*/
public class T1 extends Thread{
long count = 0L;
@Override
public void run() {
while(count < 50L) {
System.out.println(count++);//打印0-49数字
}
}
public static void main(String[] args) {
T1 t1 = new T1();
t1.start();
}
}
实现Runnable接口:
/**
* 实现Runnable接口
* @author wsz
* @date 2017年11月26日
*/
public class T2 implements Runnable{
public static void main(String[] args) {
Thread t2 = new Thread(new T2());//使用Thread类的构造函数传入Runnable接口的实例
t2.start();
}
@Override
public void run() {
int a = 0;
while(a < 50) {
System.out.println(a++);//打印0-49数字
}
}
}
2.2终止线程
package stopThread;
class User{
private int id;
private String name;
public User() {
this.id = 0;
this.name = "0";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
public class StopThread extends Thread{
public static User u = new User();
class ReadThread extends Thread{//读线程
@Override
public void run() {
while(true) {
synchronized(u) {
if(u.getId() != Integer.parseInt(u.getName())) {
System.out.println(u.toString());
break;
}
Thread.yield();
}
}
}
}
class ChangeThread extends Thread{//写线程
volatile boolean stopThread = false;
public void stopme() {
stopThread = true;
}
@Override
public void run() {
while(true) {
if(stopThread) {
System.out.println("Thread is stop");
System.out.println(u.toString());
break;
}
synchronized(u) {
long time = System.currentTimeMillis()/100000000;
u.setId((int)time);
try {
Thread.sleep(200);
System.out.println(u.toString());
} catch (InterruptedException e) {
e.printStackTrace();
}
u.setName(String.valueOf(time));
Thread.yield();//谦让
}
}
}
}
public static void main(String[] args) {
new StopThread().new ReadThread().start();
long count = 500L;
while(count > 0L) {
Thread t = new StopThread().new ChangeThread();
t.start();
// t.stop();//强制停止,将导致数据不一致
((ChangeThread) t).stopme();//自定义标识法控制线程的结束
count--;
}
}
}
2.3中断线程
验证线程中断方法Thread.interrupt(),该方法没有中断正在执行的程序退出,将会一直打印输出:
public class InterruptThread {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread() {
@Override
public void run() {
while(true) {
System.out.println("interrupteThread");
}
}
};
t1.start();
Thread.sleep(1000);
t1.interrupt();
}
}
增加中断处理方法Thread.isInterrupted(),这样线程中断便会退出程序。
public class InterruptThread {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread() {
@Override
public void run() {
while(true) {
if(Thread.currentThread().isInterrupted()) {
System.out.println("Interrupted");
break;
}
System.out.println("interrupteThread");
}
}
};
t1.start();
Thread.sleep(1000);
t1.interrupt();
}
}
Thread.sleep()将使当前线程休眠,则会抛出非运行时InterruptedException异常,需要程序捕获且处理异常。
public class InterruptThread {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread() {
@Override
public void run() {
while(true) {
if(Thread.currentThread().isInterrupted()) {
System.out.println("Interrupted");
break;
}
try {
System.out.println("interrupteThread");
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted when sleep");
//抛出异常将会清除中断标志位,需要重新设置中断标志位,
Thread.currentThread().interrupt();
}
}
}
};
t1.start();
Thread.sleep(500);
t1.interrupt();
}
}
2.4等待和通知
public class WaitAndNotify {
final static Object object = new Object();
class T1 extends Thread{
@Override
public void run() {
synchronized(object) {
System.out.println("T1 start");
try {
System.out.println("T1 wait");
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("T1 end");
}
}
}
class T2 extends Thread{
@Override
public void run() {
synchronized(object) {
System.out.println("T2 start,notify one thread");
object.notify();
System.out.println("T2 end");
}
}
}
public static void main(String[] args) {
T1 t1 = new WaitAndNotify().new T1();
T2 t2 = new WaitAndNotify().new T2();
t1.start();
t2.start();
}
}
执行结果:t1先执行并释放object锁进入等待状态;之后t2执行并通知某个线程,t2线程结束;t1线程再次获取到object锁资源,t1线程结束。
T1 start
T1 wait
T2 start,notify one thread
T2 end
T1 end
2.5挂起线程
public class SuspendThread {
public static Object object = new Object();
class ChangeThread extends Thread{
volatile boolean suspendThread = false;
public void suspendme() {
suspendThread = true;
}
public void resumeme() {
suspendThread = false;
synchronized (this) {
notify();
}
}
@Override
public void run() {
while(true) {
synchronized(this) {
while(suspendThread) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
synchronized (object) {
System.out.println("in ChangeThread");
}
Thread.yield();
}
}
}
class ReadThread extends Thread{
@Override
public void run() {
while(true) {
synchronized (object) {
System.out.println("in ReadThread");
}
Thread.yield();
}
}
}
public static void main(String[] args) throws InterruptedException {
ChangeThread changeThread = new SuspendThread().new ChangeThread();
ReadThread readThread = new SuspendThread().new ReadThread();
changeThread.start();
readThread.start();
Thread.sleep(100);
changeThread.suspendme();//挂起
System.out.println("suspend changeThread 1s");
Thread.sleep(100);
System.out.println("resume changeThread");
changeThread.resumeme();//继续执行
}
}
2.6等待与谦让线程
public class JoinAndYield {
public volatile static long i = 0L;
class AddThread extends Thread{
@Override
public void run() {
for(i = 0L;i<500000L;i++);
}
}
public static void main(String[] args) throws InterruptedException {
AddThread addThread = new JoinAndYield().new AddThread();
addThread.start();
// addThread.join(); //不使用join,i的值将达不到循环最大值。
System.out.println(i);
}
}