Java线程的暂停与恢复

 Java以前的suspend和resume方法过时不建议使用。

那怎么办呢?

具体说起来比较复杂,需要暂停标志加synchronized+等待/唤醒

详见代码

 

package defaul;


import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;


public class ThreadSuspendframe extends JFrame{
	private JLabel label;//显示数字中的标签
	String[] numb = {"15180691681","13870225947","13870261079","12345671111","1397995240"};
	public ThreadSuspendframe(){
		setTitle("手机号抽奖");
		setBounds(200, 200, 400, 400);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		MyThread myThread = new MyThread();
		myThread.start();
		label = new JLabel("0");//实例化标签 初始化为0
		label.setHorizontalAlignment(SwingConstants.CENTER);//设置文字居中
		label.setFont(new Font("宋体", Font.BOLD, 42));//设置字体
		getContentPane().add(label, BorderLayout.CENTER);
		JButton jButton = new JButton("暂停");
		jButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				String Btn = jButton.getText();
				if(Btn.equals("暂停"))
				{
					myThread.toSuspend();
					jButton.setText("继续");
				}else{
					myThread.toResume();
					jButton.setText("暂停");
				}
			}
		});
		getContentPane().add(jButton, BorderLayout.SOUTH);
		setVisible(true);
	}
	class MyThread extends Thread{
		
		private boolean suspend = false;
		
		public synchronized void toSuspend(){
			suspend = true;
		}
		
		public synchronized void toResume(){
			notify();//当前等待的线程继续执行
			suspend = false;
		}
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			while(true){
				
				synchronized (this) {
				while(suspend){
					try {
						wait();//让线程进入等待状态
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				}
				int randomNum = new Random().nextInt(numb.length);//获取数组随机索引
				String phone = numb[randomNum];
				label.setText(phone);
			}
		}
	}
	public static void main(String[] args) {
		new ThreadSuspendframe();
	}
}

猜你喜欢

转载自blog.csdn.net/qq_41603898/article/details/88626953