1.使用線程的stop方法,但是這個方法已經被deprecated了,因為使用它會釋放鎖並停掉線程,但是會出現數據不一致以及重要資源不能正確釋放的問題
2.使用interrupt方法:調用線程的這個方法會修改線程的中斷標志位真,可以通過interrupted和isInterrupted這兩個方法來判斷線程是否已經被中斷,區別是第一個方法在調用之后會把狀態改為false,第二個方法則不會
使用interrupt方法來中斷一個線程執行的代碼實現如下:
package com.zcj.thread01;
public class StopThread {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable01());
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
thread.interrupt();
}
}
class Runnable01 implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
try{
while(true){
System.out.println("線程一直執行中");
//有二種方式來中斷線程的執行,不采取任何措施的話,線程會進行到執行完
//第一種:使用拋出異常的辦法
if(Thread.currentThread().interrupted()){
System.out.println("線程被中斷了");
throw new InterruptedException();
}
//第二種:使用return;但是一般推薦第一種
//if(Thread.currentThread().interrupted()){
//System.out.print("線程被中斷了");
//return;
//}
}
}catch(InterruptedException e){
e.printStackTrace();
return;
}
}
}
3.暫停線程:已經廢棄的suspend和resume方法
會出現獨占的情況:因為即使使用suspend暫停了線程,但是線程並不會釋放自身所占用的鎖,這樣會導致資源的獨占,甚至會出現死鎖的情況
會出現數據不一致的情況:一個線程修改了部分數據然后掛起,另外一個線程讀取數據,但是這個可以使用共享資源的同步來解決
下面演示了死鎖的情況:
package com.zcj.thread02;
public class DeathLock {
private String lock1 ="lock1";
private String lock2 ="lock2";
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
DeathLock death = new DeathLock();
Thread thread01 = new Thread(death.new Runnable01());
Thread thread02 = new Thread(death.new Runnable02());
thread01.start();
thread02.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
thread01.resume();
thread02.resume();
}
class Runnable01 implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
synchronized(lock1){
System.out.println("線程1獲得了鎖1");
System.out.println("線程1暫停了");
Thread.currentThread().suspend();
System.out.println("線程1恢復了");
synchronized(lock2){
System.out.println("線程1獲得了鎖2");
}
}
}
}
class Runnable02 implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
synchronized(lock2){
System.out.println("線程2獲得了鎖2");
System.out.println("線程2暫停了");
Thread.currentThread().suspend();
System.out.println("線程2恢復了");
synchronized(lock1){
System.out.println("線程2獲得了鎖1");
}
}
}
}
}
線程1獲得了鎖1線程1暫停了線程2獲得了鎖2線程2暫停了線程2恢復了線程1恢復了從運行結果來看,這里發生了死鎖,導致線程1不能獲得2鎖,線程2不能獲得1鎖