【JAVA】挂起、恢复和停止线程的示例代码

本文通过一个具体的Java8代码示例展示了如何控制线程的开始、挂起及恢复运行。示例中定义了一个实现了Runnable接口的NewThread类,通过设置suspendFlag标志位并结合synchronized块和wait()、notify()方法来实现线程的挂起和恢复。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//代码示例来自于《Java 8 编程官方参考教程 第9版》
package com.app.practice;
//控制线程的开始,挂起和结束
//Suspending and resuming a thread the modern way.
class NewThread implements Runnable{
	String name;//name of thread
	Thread t;
	boolean suspendFlag;
	
	NewThread(String threadname){
		name = threadname;
		t = new Thread(this, name);
		System.out.println("New thread: "+t);
		suspendFlag = false;
		t.start();//Start the thread
	}
	
	//This is the entry point for thread.
	public void run(){
		try{
			for(int i = 15;i>0;i--){
				System.out.println(name+": "+i);
				Thread.sleep(200);
				synchronized (this) {
					while(suspendFlag){
						wait();
					}
				}
			}
		}catch (InterruptedException e){
			System.out.println(name + " interrupted.");
		}
		System.out.println(name +" exiting.");
	}
	
	synchronized void mysuspend(){
		suspendFlag=true;
	}
	
	synchronized void myresume(){
		suspendFlag = false;
		notify();
	}
}
public class SuspendResume {

	public static void main(String[] args) {
		NewThread ob1 = new NewThread("One");
		NewThread ob2 = new NewThread("Two");
		
		try{
		Thread.sleep(1000);
		ob1.mysuspend();
		System.out.println("Suspending thread One");
		Thread.sleep(1000);
		ob1.myresume();
		System.out.println("Resuming thread One");
		ob2.mysuspend();
		System.out.println("Suspending thread Two");
		Thread.sleep(1000);
		ob2.myresume();
		System.out.println("Resuming thread Two");
		}catch(InterruptedException e){
			System.out.println("Main thread Interrupted");
		}
		
		//wait for threads to finish
		try{
			System.out.println("Waiting for threads to finish.");
			ob1.t.join();
			ob2.t.join();
		}catch (InterruptedException e){
			System.out.println("Main thread Interrupted");
		}
		
		System.out.println("Main thread exiting.");
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值