好记性不如铅笔头

java, think_in_java, 编程

《Java编程思想》读书笔记:interrupt && join

最近在整理 Java 的多线程相关的技术,这里备份下关于【 interrupt && join 】代码。

github:

【 https://github.com/cstriker1407/think_in_java 】

interrupt主要用来打断线程,让线程可以停止休眠,join注意用于等待线程停止。

CONTENTS

ThreadSample2.java类:

public class ThreadSample2
{
	public static void test()
	{
		Sample2Thread thread = new Sample2Thread();
		thread.start();
		try
		{
			Thread.sleep(1500);
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
		System.out.println("the Main is begin to interrupt");
		thread.interrupt();
		System.out.println("the Main is finish");
	}
	public static void test2()
	{
		Sample2Thread thread = new Sample2Thread();
		thread.start();
		try
		{
			Thread.sleep(1500);
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
		System.out.println("the Main is begin to join");
		try
		{
			thread.join();
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
		System.out.println("the Main is finih");
	}
}
class Sample2Thread extends Thread
{
	@Override
	public void run()
	{
		System.out.println("the Sample2Thread is begin to start");

		try
		{
			Thread.sleep(5000);
		}
		catch (InterruptedException e)
		{
			System.out.println("the Sample2Thread is interrupted");
		}finally
		{
			System.out.println("the Sample2Thread is finish");
		}
	}
}

 日志打印:

the Sample2Thread is begin to start
the Main is begin to interrupt
the Main is finish
the Sample2Thread is interrupted
the Sample2Thread is finish 
the Sample2Thread is begin to start
the Main is begin to join
the Sample2Thread is finish
the Main is finih

 备注:

发表评论

19 − 15 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据