前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java线程的暂停与恢复

Java线程的暂停与恢复

作者头像
用户2965768
发布2019-03-20 10:42:41
2.2K0
发布2019-03-20 10:42:41
举报
文章被收录于专栏:wymwym

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

那怎么办呢?

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

详见代码

代码语言:javascript
复制
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();
	}
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019年03月17日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档