利用Semaphore线程一直输出字符串,可以进行暂停,停止,重新开始

本文介绍了一个使用Java Swing实现的GUI程序案例,该程序能够通过按钮控制一个线程的运行与暂停状态。利用Semaphore信号量来同步线程,实现了线程间的协作。

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

import java.awt.*;
import java.awt.event.*;
import java.util.concurrent.*;

import javax.swing.*;

public class RunAndStop {
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				JFrame frame = new RunAndStopFrame();
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				frame.setVisible(true);
			}
		});
	}
}

class RunAndStopFrame extends JFrame {
	public RunAndStopFrame() {
		setTitle("Run and Stop");
		
		RunAndStopComponent component = new RunAndStopComponent();
		add(component, BorderLayout.CENTER);
		
		final RunAndStopThread runAndStop = new RunAndStopThread(component);
		
		final JButton runButton = new JButton("运行");
		runButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent event) {
				if(runAndStop.getRun()) {
					//处于暂停状态
					runButton.setText("运行");
					runAndStop.setStop();
				} else {
					//处于运行状态
					if(first) {
						//是第一次运行程序,才调用start方法,并且控制整个程序的flag置为true
						first = false;
						runAndStop.setFlag(true);
						Thread t = new Thread(runAndStop);
						t.start();
					}
					
					runButton.setText("暂停");
					runAndStop.setRun();
				}
			}
		});
		
		JButton stepButton = new JButton("停止");
		stepButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent event) {
				//停止程序
				runAndStop.setFlag(false);
				runButton.setText("重新开始");
				first = true;
				runAndStop.setStop();
			}
		});
		
		JPanel buttons = new JPanel();
		buttons.add(runButton);
		buttons.add(stepButton);
		add(buttons, BorderLayout.SOUTH);
		setSize(300, 300);
	}
	
	public static boolean first = true;
}
class RunAndStopThread implements Runnable {

	public RunAndStopThread(RunAndStopComponent component) {
		this.component = component;
		this.gate = new Semaphore(1);
		this.run = false;
		this.flag = false;
	}
	
	public void setRun() {
		run = true;
		gate.release();
	}
	
	public void setStop() {
		run = false;
		gate.release();
	}
	
	public boolean getRun() {
		return this.run;
	}
	
	public void setFlag(boolean flag) {
		this.flag = flag;
	}
	
	@Override
	public void run() {
		int i = 0;
		try {
			while(flag) {
				if(run) {
					component.setString("this is a test String." + i);
					i++;
					Thread.sleep(800);
				} else {
					gate.acquire();
				}
			}
			
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
		}
	}
	
	private RunAndStopComponent component;
	private Semaphore gate;
	private volatile boolean run;//控制开始和暂停
	private volatile boolean flag;//控制整个程序停止
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值