JAVA线程

本文通过两个示例展示了Java中线程的join方法和interrupt方法的使用方式。join方法用于等待一个线程完成其任务,而interrupt方法则用于中断正在等待或阻塞状态的线程。

线程的各种状态如上图所看到的。

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

转载于:https://www.cnblogs.com/yutingliuyl/p/6791876.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值