Java高并发编程---线程基本使用

线程构造
private void init(ThreadGroup g, Runnable target, String name,long stackSize,AccessControlContext acc) {
	if (name == null) {
		throw new NullPointerException("name cannot be null");
	}
	// 当前线程就是该线程的父线程
	Thread parent = currentThread();
	this.group = g;
	// 将daemon、priority属性设置为父线程的对应属性
	this.daemon = parent.isDaemon();
	this.priority = parent.getPriority();
	this.name = name.toCharArray();
	this.target = target;
	setPriority(priority);
	// 将父线程的InheritableThreadLocal复制过来
	if (parent.inheritableThreadLocals != null)
	this.inheritableThreadLocals=ThreadLocal.createInheritedMap(parent.
	inheritableThreadLocals);
	// 分配一个线程ID
	tid = nextThreadID();
}

 一个新构造的线程对象是由其parent线程来进行空间分配的,而child线程继承了parent是否为Daemon、优先级和加载资源的contextClassLoader以及可继承的ThreadLocal,同时还会分配一个唯一的ID来标识这个child线程。至此,一个能够运行的线程对象就初始化好了,在堆内存中等待着运行。

线程启动

 线程对象在初始化完成之后,调用start()方法就可以启动这个线程。线程start()方法的含义是:当前线程(即parent线程)同步告知Java虚拟机,只要线程规划器空闲,应立即启动调用start()方法的线程。
启动一个线程前,最好为这个线程设置线程名称,因为这样比较方便在使用jstack分析程序或者进行问题排查。

理解中断

 中断可以理解为线程的一个标识位属性,它表示一个运行中的线程是否被其他线程进行了中断操作。中断好比其他线程对该线程打了个招呼,其他线程通过调用该线程的interrupt()方法对其进行中断操作。
 在理解中断中,有两个方法非常重要:

  • interrupt()
  • isInterrupted()

 interrupt()方法是用于中断线程,而isInterrupted()方法是用于判断线程自身是否被中断了。这两个方法都是对自己这个线程使用的。
 许多声明抛出InterruptedException的方法(例如Thread.sleep(longmillis)方法)这些方法在抛出InterruptedException之前,Java虚拟机会先将该线程的中断标识位清除,然后抛出InterruptedException,此时调用isInterrupted()方法将会返回false。

suspend()、resume()和stop()

 这三个方法就是暂停、恢复和停止。
但是,这三个方法其实已经是过时的了,不建议使用,因为在调用后,线程不会释放已经占有的资源(比如锁),而是占有着资源进入睡眠状态,这样容易引发死锁问题。
 所以,这些过时的方法被现在的等待/通知机制来替代了。

终止线程(安全)

 其实之前提到的中断状态是线程的一个标识位,其中断操作是最适合用来取消或停止任务的线程间交互方式。

public class Shutdown {
	public static void main(String[] args) throws Exception {
			Runner one = new Runner();
			Thread countThread = new Thread(one, "CountThread");
			countThread.start();
			// 睡眠1秒,main线程对CountThread进行中断,使CountThread能够感知中断而结束
			TimeUnit.SECONDS.sleep(1);
			countThread.interrupt();
			Runner two = new Runner();
			countThread = new Thread(two, "CountThread");
			countThread.start();
			// 睡眠1秒,main线程对Runner two进行取消,使CountThread能够感知on为false而结束
			TimeUnit.SECONDS.sleep(1);
			two.cancel();
		}
		private static class Runner implements Runnable {
				private long i;
				private volatile boolean on = true;
				
				@Override
				public void run() {
					while (on && !Thread.currentThread().isInterrupted()){
						i++;
					}
					System.out.println("Count i = " + i);
				}
				public void cancel() {
					on = false;
				}
		}
}

输出结果:

Count i = 543487324
Count i = 540898082

 示例在执行过程中,main线程通过中断操作和cancel()方法均可使CountThread得以终止。这种通过标识位或者中断操作的方式能够使线程在终止时有机会去清理资源,而不是武断地将线程停止,因此这种终止线程的做法显得更加安全和优雅。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值