Java中我们经常会用到多线程,多线程使用完之后要注意终止线程,防止内存泄露等问题。在介绍之前先说说 多线程中一个比较好用的函数 ,join() 函数
join()函数
join() 函数使得主线程等待调用该函数的线程执行完之后才继续执行,该方法用于主线程等待子线程的返回结果,用该返回结果继续执行主线程后面的代码,使用方法如下:
FirstThread thread1 = new FirstThread();
thread1.start();
thread1.join();
//调用join()函数后,下面这句打印语句得等到thread1执行完才会打印,若没有调用该函数,则thread1.start()后就打印出下面语句
System.out.println("线程退出");
==========================华丽分割线============================================
根据线程运行的状态,结束进程可以分为以下两种情况:1、结束正在运行的进程 2、结束非运行状态的线程
结束正在运行的进程
方法:设置全局变量作为run方法执行时的判别依据,修改该变量的值时退出线程。使用方法如下:
class FirstThread extends Thread
{
//用关键字volatile设置变量为线程同步,即这个变量在某一个线程中被修改,其他地方的这个变量的值会被立即修改,这点在这里非常关键,能够在修改标识符时及时退出线程
public volatile boolean exit = false;
int count = 0;
public void run()
{
System.out.println(getName()+"is starting");
//执行run()方法前监测变量exit的值,若为true 则退出线程
while(!exit)
{
System.out.println(getName()+"is runing"+count++);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println(getName()+"即将从阻塞中退出");
System.out.println("this.isInterrupted()"+this.isInterrupted());
}
//使用条件退出线程
if(count == 10)
{
exit = true;
}
}
}
}
public class llp_java
{
public static void main(String[] args) throws InterruptedException
{
FirstThread thread1 = new FirstThread();
thread1.start();
//或在主函数中直接结束线程
thread1.exit = true;
System.out.println("线程退出");
}
}
结束非运行状态的线程:
如果线程调用了可中断等待方法,正处于等待状态,此时并是执行run()方法中的while循环,无法根据前面的全局变量的判定退出线程。此时可以通过调用Thread的interrupt方法让等待方法抛出InterruptedException异常,然后在循环外截获并处理异常,这样便跳出了线程run方法中的循环,以使线程顺利结束。使用方法如下:
class FirstThread extends Thread
{
//用关键字volatile设置变量为线程同步,即这个变量在某一个线程中被修改,其他地方的这个变量的值会被立即修改,这点在这里非常关键,能够在修改标识符时及时退出线程
public volatile boolean exit = false;
int count = 0;
public void interrupt()
{
//复写中断函数,改变exit的状态
exit = true;
}
public void run()
{
System.out.println(getName()+"is starting");
while(!exit)
{
System.out.println(getName()+"is runing"+count++);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
//捕获阻塞中断后调用interrupted()函数,结束线程
Thread.interrupted();
System.out.println(getName()+"即将从阻塞中退出");
System.out.println("this.isInterrupted()"+this.isInterrupted());
}
//if(count == 10)
//{
// exit = true;
//}
}
}
}
public class llp_java
{
public static void main(String[] args) throws InterruptedException
{
FirstThread thread1 = new FirstThread();
thread1.start();
//直接调用中断函数,或者有阻塞中断发生时,会自动调用该函数
thread1.interrupt();
// thread1.join();
System.out.println("线程退出");
}