Thread

设置线程优先级

线程的优先级不能小于1也不能大于10,指定线程优先级不能大于线程所在组的优先级,线程默认优先级为5,即与它的父线程(main)保持一致。

//为线程设定优先级
public final void setPriority(int newPriority)
//获取线程优先级
public final int getPriority

获取线程ID

//获取线程的唯一ID
public long getId()

获取当前线程

//用于返回当前执行线程的引用
public static Thread currentThread()

线程interrupt

如下方法的调用会导致线程阻塞,而调用当前线程的interrupt方法,就可以打断阻塞

Object.wait()
Thread.sleep()
Thread.join()
...

在一个线程的内部存在着名为interrupt flag的标识,如果一个线程被interrupt,那么它的flag将被设置,但是可中断方法会捕获中断异常,从而导致flag被清除,这样不会影响线程中其它方法的执行。

public void interrupt()

isInterrupted是Thread的一个成员方法,它主要判断当前线程是否被中断,该方法仅是对interrupt flag标识的一个判断,并不会影响标识发生任何改变。

public boolean isInterrupted()

interrupted是一个静态方法,用于判断当前线程是否被中断,但是它和成员方法isInterrupted有很大区别,调用该方法会直接擦除掉线程的interrupt flag标识

public static boolean interrupted()

join方法

在主线程里面调用线程A的join方法,会使得主线程进入等待,此时主线程是BLOCKED状态的,直至A结束生命周期。
下面的例子说明了,在执行子线程的join方法后,如果子线程的生命周期没有结束,那么主线程就会一直处于BLOCKED状态。

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.toList;

public class ThreadJoin {

	public static void main(String [] args) throws InterruptedException {
		//定义两个线程,并保存在threads中
		List<Thread> threads= IntStream.range(1, 3).mapToObj(ThreadJoin::create).collect(toList());
		//启动两个线程
		threads.forEach(Thread::start);
		//执行join方法
		for(Thread thread: threads) {
			thread.join();
		}
		for(int i=0;i<10;i++) {
			System.out.println(Thread.currentThread().getName()+"*"+i);
			shortSleep();
		}
	}

	private static Thread create(int seq) {
		return new Thread(()->
		{
			for(int i=0;i<10;i++) {
				System.out.println(Thread.currentThread().getName()+"*"+i);
			}
		},String.valueOf(seq));
	}
	
	private static void shortSleep() {
		try {
			TimeUnit.SECONDS.sleep(1);
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
}

关闭线程

判断interrupt flag标识

Thread thread = new Thread() {
			public void run() {
				while(!isInterrupted()) {
					//working
				}
			}
		};
		thread.start();		
		thread.interrupt();

捕获中断信号

Thread thread1 = new Thread() {
			public void run() {
				for(;;) {
					try {
						TimeUnit.MINUTES.sleep(1);
					}catch(Exception e) {
						break;
					}
				}
			}
		};
		thread1.start();		
		thread1.interrupt();

volatile开关

public class TestThread extends Thread{

	private volatile boolean closed = false;
	
	public static void main(String [] args) {
		TestThread thread= new TestThread();
		thread.start();
		thread.close();
	}
	
	public void run() {
		while(!closed && !isInterrupted()) {
			//working
		}
	}
	
	public void close() {
		this.closed = true;
		this.interrupt();
	}
	
}

线程通信方式

通过synchronized关键字实现通信,即wait/notify机制

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值