【Java】线程常用方法

1.currentThread,用于返回执行这段代码的线程。同一段代码可能被运行多次,因此currentThread与执行的代码无关,而与执行代码的线程有关。

 

public class TThread implements Runnable{

	public TThread(){
		System.out.println(Thread.currentThread().getName());
	}
	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName());
	}

	public static void main(String args[]){
		Thread t = new Thread(new TThread());
		t.setName("a");
		t.start();
	}
}


TThread的构造方法和run方法都是属于TThread类的,但是执行之后,构造方法是在main线程内执行的,run方法是在t线程内执行的。所以该方法只看执行的线程,不看代码块。

 

2.与进程中断相关的三个方法。

interrupt():用于中断一个线程,但是事实上它会中断吗?看一个例子。

 

public class TThread implements Runnable{

	@Override
	public void run() {
		for(int i = 0; i < 10000; i++){
			System.out.println(i + " ");
		}
	}

	public static void main(String args[]){
		Thread t = new Thread(new TThread());
		t.setName("a");
		t.start();
		t.interrupt();
	}
}

结果i到了10000,但是已经调用了t的interrupt方法了,说明这个方法并不能打断。事实上,它仅仅是给被调用的线程打上一个中断的标记,然后如果确实要中断,那必须检测到这个标记,然后做进一步的处理才行。
 

 

interrupted():是一个静态方法,返回当前运行的线程的打断状态。因为是返回当前的,所以这是一个静态方法。

isIntercepted(); 非静态方法,返回调用者的打断状态。

 

	@Override
	public void run() {
		for(int i = 0; i < 10000; i++){
			//System.out.println(i + " ");
		}
	}

	public static void main(String args[]){
		Thread t = new Thread(new TThread());
		t.setName("a");
		t.start();
		t.interrupt();
		//Thread.currentThread().interrupt();
		System.out.println(""+t.getName()+ " "+t.isInterrupted());
		System.out.println(""+Thread.currentThread().getName()+" "+Thread.interrupted());
	}

这段代码会显示上述两个检测方法的区别之一。如果只让t中断,那么通过调用非静态的检测方法,可以得到t的状态是true的。但是当前线程是main,所以静态方法返回的是false。

 


如果把注释去掉,那么当前线程也就是main,也会停止,会返回true。

这两个方法的另一个区别是,interrupted方法返回状态以后,会清除掉标记,如果调用两次,第二次会返回false。isInterrupted不会清除。

 

@Override
	public void run() {
		for(int i = 0; i < 10000; i++){
			//System.out.println(i + " ");
		}
	}

	public static void main(String args[]){
		Thread t = new Thread(new TThread());
		t.setName("a");
		t.start();
		t.interrupt();
		//Thread.currentThread().interrupt();
		System.out.println(""+t.getName()+ " "+t.isInterrupted());
		System.out.println(""+t.getName()+ " "+t.isInterrupted());
	}


那么该如何停止一个线程?通常采用异常。

 

 

public class TThread implements Runnable{

	@Override
	public void run() {
		try{
		for(int i = 0; i < 10000; i++){
			System.out.println(i);
			if(Thread.interrupted()){
				throw new InterruptedException();
			}
		}
		
		}catch(InterruptedException e){
			System.out.println("break");
		}
	}

	public static void main(String args[]){
		Thread t = new Thread(new TThread());
		t.setName("a");
		t.start();
		t.interrupt();
	}
}


run方法不断检测状态,一旦打断,就抛异常,然后退出。

 

如果线程里执行阻塞方法比如wait,sleep等被中断时,会抛出InterruptedExceprion。如果不是执行阻塞方法,那么只能在线程里用循环不断检测标志来处理中断。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值