JAVA線程

線程的各種狀態如上圖所示。

對於wait/notify的測試,我將會留到 生產者消費者模式中實現。

對於join、interrupt的測試如下:

package com.huan;

public class ThreadTest {
	
	public static void main(String[] args) throws Exception{
//		joinTest();
		interruptTest();
	}
	
	public static void joinTest(){
		new Thread(){
			@Override
			public void run() {
				Thread t1 = new Thread(){
					@Override
					public void run() {
						try {
							Thread.sleep(3000);
							System.out.println("//t1 thread");
						} catch (InterruptedException e) {
							System.out.println("//sleep interrupted");
						}

					}

				};
				t1.start();
				try {
					t1.join();
				} catch (InterruptedException e) {
					System.out.println("//join interrupted");
				}
				System.out.println("//out thread");
			}
		}.start();
		
		//t1 thread
		//out thread
	};
	
	public static void interruptTest(){
		new Thread(){
			@Override
			public void run() {
				Thread t1 = new Thread(){
					@Override
					public void run() {
						try {
							Thread.sleep(3000);
							System.out.println("//t1 thread");
						} catch (InterruptedException e) {
							System.out.println("//sleep interrupted");
						}

					}

				};
				t1.start();
				System.out.println("//out thread");
				t1.interrupt();
			}
		}.start();
		//out thread
		//sleep exception
	};
	
}

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