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
	};
	
}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。