如何从另一个线程暂停和恢复Java中的线程
我正在用JavaSwing编写一个应用程序。我需要的是一个过程,在这个过程中,我可以使用图形界面中的按钮停止“精化”线程 这里有一个简单的项目,重点是我需要什么如何从另一个线程暂停和恢复Java中的线程,java,multithreading,swing,Java,Multithreading,Swing,我正在用JavaSwing编写一个应用程序。我需要的是一个过程,在这个过程中,我可以使用图形界面中的按钮停止“精化”线程 这里有一个简单的项目,重点是我需要什么 import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JTextArea; /* * To change this template, choose Tools | Templates * and open the t
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextArea;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Nikola
*/
public class Main extends javax.swing.JFrame
{
private MyThread THREAD;
public Main()
{
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("Pause Thread");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jButton2.setText("Resume Thread");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("Start Thread");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 63, Short.MAX_VALUE)
.addComponent(jButton2)
.addGap(18, 18, 18)
.addComponent(jButton1))
.addComponent(jScrollPane1))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3))
.addContainerGap())
);
pack();
}// </editor-fold>
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)
{
THREAD = new MyThread(jTextArea1);
THREAD.start();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
try
{
THREAD.pauseThread();
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
THREAD.resumeThread();
}
public static void main(String args[])
{
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try
{
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
{
if ("Nimbus".equals(info.getName()))
{
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}
catch (ClassNotFoundException ex)
{
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
catch (InstantiationException ex)
{
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
catch (IllegalAccessException ex)
{
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
catch (javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new Main().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration
}
class MyThread extends Thread
{
JTextArea area;
private final Object lock = new Object();
public MyThread(JTextArea area)
{
super();
this.area = area;
}
@Override
public void run()
{
for(int i=0 ; ; i++)
area.setText(i+"");
}
public void pauseThread() throws InterruptedException
{
synchronized(lock)
{
lock.wait();
}
}
public void resumeThread()
{
synchronized(lock)
{
lock.notify();
}
}
}
import java.util.logging.Level;
导入java.util.logging.Logger;
导入javax.swing.JTextArea;
/*
*要更改此模板,请选择工具|模板
*然后在编辑器中打开模板。
*/
/**
*
*@作者尼古拉
*/
公共类Main扩展了javax.swing.JFrame
{
私有线程;
公用干管()
{
初始化组件();
}
@抑制警告(“未选中”)
//
私有组件(){
jButton1=newjavax.swing.JButton();
jScrollPane1=newjavax.swing.JScrollPane();
jTextArea1=newjavax.swing.JTextArea();
jButton2=newjavax.swing.JButton();
jButton3=newjavax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setText(“暂停线程”);
jButton1.addActionListener(新java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
jButton1ActionPerformed(evt);
}
});
jTextArea1.设置列(20);
jTextArea1.设置行(5);
jScrollPane1.setViewportView(jTextArea1);
setText(“恢复线程”);
jButton2.addActionListener(新java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
jButton2ActionPerformed(evt);
}
});
setText(“开始线程”);
jButton3.addActionListener(新java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
JButton3执行的操作(evt);
}
});
javax.swing.GroupLayout=newjavax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(布局);
layout.setHorizontalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,63,Short.MAX_值)
.addComponent(jButton2)
.addGap(18,18,18)
.addComponent(jButton1))
.addComponent(jScrollPane1))
.addContainerGap())
);
layout.setVerticalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1,javax.swing.GroupLayout.DEFAULT\u SIZE,244,Short.MAX\u值)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3))
.addContainerGap())
);
包装();
}//
私有void jButton3ActionPerformed(java.awt.event.ActionEvent evt)
{
线程=新的MyThread(jTextArea1);
THREAD.start();
}
私有void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
尝试
{
THREAD.pauseThread();
}
捕获(中断异常例外)
{
例如printStackTrace();
}
}
私有void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
THREAD.resumeThread();
}
公共静态void main(字符串参数[])
{
/*
*设置Nimbus的外观和感觉
*/
//
/*
*如果Nimbus(在JavaSE6中引入)不可用,请使用
*默认外观。有关详细信息,请参阅
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
尝试
{
for(javax.swing.UIManager.LookAndFeelInfo:javax.swing.UIManager.getInstalledLookAndFeels())
{
if(“Nimbus”.equals(info.getName()))
{
setLookAndFeel(info.getClassName());
打破
}
}
}
捕获(ClassNotFoundException ex)
{
getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}
catch(实例化异常)
{
getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}
捕获(非法访问例外)
{
getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}
catch(javax.swing.UnsupportedLookAndFeelException ex)
{
getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}
//
/*
*创建并显示表单
*/
invokeLater(new Runnable())
{
公开募捐
{
new Main().setVisible(true);
}
});
}
//变量声明-不修改
私有javax.swing.JButton jButton1;
私有javax.swing.JButton jButton2;
私有javax.swing.JButton jButton3;
私有javax.swing.JScroll
class MyThread extends Thread {
private volatile boolean running = true; // Run unless told to pause
...
@Override
public void run()
{
for(int i=0 ; ; i++)
{
// Only keep painting while "running" is true
// This is a crude implementation of pausing the thread
while (!running)
yield;
area.setText(i+"");
}
public void pauseThread() throws InterruptedException
{
running = false;
}
public void resumeThread()
{
running = true;
}
}
class MyThread extends Thread {
JTextArea area;
private final Object GUI_INITIALIZATION_MONITOR = new Object();
private boolean pauseThreadFlag = false;
public MyThread(JTextArea area) {
super();
this.area = area;
}
@Override
public void run() {
for(int i=0 ; ; i++) {
checkForPaused();
area.setText(i+"");
}
}
private void checkForPaused() {
synchronized (GUI_INITIALIZATION_MONITOR) {
while (pauseThreadFlag) {
try {
GUI_INITIALIZATION_MONITOR.wait();
} catch (Exception e) {}
}
}
}
public void pauseThread() throws InterruptedException {
pauseThreadFlag = true;
}
public void resumeThread() {
synchronized(GUI_INITIALIZATION_MONITOR) {
pauseThreadFlag = false;
GUI_INITIALIZATION_MONITOR.notify();
}
}
}