【Java高併發學習】Thread線程相關

Thread線程相關

1.線程生命週期


Thread類中定義的線程枚舉狀態:
  1. NEW:線程剛剛創建,但沒有開始執行start
  2. RUNNABLE:線程所需運行的資源均已準備完成
  3. BLOCKED:線程執行時遇到同步塊時,進入阻塞狀態,直到獲取到請求的鎖信息
  4. WAITING:進入無時間限制的等待狀態
  5. TIMED.WAITING:進入有限時間的等待狀態
  6. 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);
	}
}

發佈了54 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章