java暂停或停止_java多線程---停止、暫停一個線程

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鎖

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值