线程静态方法sleep()详解以及唤醒线程方法interrupt

//java多线程中的sleep方法,这是一个手动给线程加阻塞的一个方法,当调用sleep方法后线程从运行到阻塞等阻塞时间过后到就绪状态。sleep是一个静态方法因此直接通过Thread调用他与线程对象名无关。

//下面代码中有一个注意点:在main方法中有一句t1.sleep(2000),是t1线程启动后2s才运行吗?不是,这里就要注意因为sleep是一个静态方法,因此和线程对象是无关的,要看他现在在哪个栈内存中,也就是看他当前在哪个线程中,很明显他现在主线程中,主线程调用类中的main方法,所以也就是当t1.start()后,t1线程已经开始运行,当2s后运行主线程中的输出语句“Hello world”所以见代码:

package ThreadTest;

class Processor06 implements Runnable{
	@Override
	public void run() {		//注意run方法不抛出异常,所以覆写的run方法不抛出异常
		// TODO Auto-generated method stub
		for(int i=0; i<20; i++){
			System.out.println(Thread.currentThread().getName() + "-->" + i);
			try {
				Thread.sleep(1000);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}
}

public class ThreadTest06 {

	public static void main(String[] args) throws InterruptedException  {
		Thread t1 = new Thread(new Processor06());
		t1.setName("t1");
		t1.start();
		t1.sleep(2000);		
			//这里要注意sleep是一个静态方法通过Thread直接调用的跟t1这个类无关,写的时候应该Thread.sleep()
		System.out.println("Hello world");
	}
}

//运行截图,因为t1线程我设置的是1s阻塞一次,也就是1s获得一个时间片,那么2s后执行Hello world 

//下面是唤醒线程的方法interrupt

package ThreadTest;

class Processor07 implements Runnable{
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			Thread.sleep(10000000000000L);
			System.out.println("Sleep is end");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		for(int i=0; i<20; i++){
			System.out.println(Thread.currentThread().getName() + "-->" + i);
		}
	}
}

public class ThreadTest07 {
	public static void main(String[] args) throws InterruptedException {
		Thread t1 = new Thread(new Processor07());
		t1.setName("t1");
		t1.start();
		Thread.sleep(5000);
		t1.interrupt();
	}
}

猜你喜欢

转载自blog.csdn.net/small__snail__5/article/details/81297254