我正在用Java Swing編寫應用程式.我需要的是一个可以使用圖形介面中的按钮停止"阐述"執行緒的過程。
這是一个专註於我需要的簡單專案
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();
}
}
}
問题很簡單: 在實際的應用程式中,使用者設置一些選項,然後啟動執行緒,對選定的資料进行详细說明。
我想提供一个"暂停"按钮,以便使用者可以暂時停止详细說明並进行必要的檢查,然後可以恢複操作。
我編碼的方式是停止的圖形執行緒,而不是"精化"執行緒。
如果執行示例代碼並按"開始",則文字區域開始計數.我需要的最终結果是,当我按下"暂停"按钮時,執行緒进入"睡眠"狀態,計數停止;当我按下"恢複"按钮時,執行緒"唤醒",文字區域中的計數開始
最新回復
- 3月前1 #
- 3月前2 #
像這樣尝試:
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(); } } }
最好像您一樣使用监视器.但是您不能从外面強製等待.您必须告诉執行緒等待,直到再次(通過监视器)通知他為止.在這種情况下,您只有這種簡單的方法
checkForPaused()
您將不得不摆上重要的位置,這樣就不会有很长的延迟,直到執行緒暂停為止。您還可以擴充套件此功能,以便可以詢問執行緒是否因在
checkForPaused()
中設置的標志而被暂停 和一个public boolean isPausing()
相似問題
- java:哪些Swing元件方法是執行緒安全的?javaswingthreadsafety2021-01-12 01:26
- java:自動調整JTable列的宽度javaswingjtabletablecolumn2021-01-11 22:58
- java:如何在Swing中為JTable提供分頁支援?javaswingpaginationjtable2021-01-11 10:54
- java:从jar載入圖像以进行Swing HTMLjavahtmlimageswing2021-01-11 04:58
您無法明確地以您想要的方式暂停另一个執行緒。
您需要做的是signal,另一个執行緒應该通過設置某種標志来停止.有問题的執行緒必须具有邏輯来檢查该標志並在發生這種情况時暂停其工作。
因此在這種情况下,也许可以更改
MyThread
如下:這是一个粗略的例子,為簡潔起见,它使用了一種自旋鎖而不是基於监视器的適当睡眠.希望它傳達了您如何使用標志来控製執行緒暂停的想法。
請註意,如果您在塊中執行了一些长時間執行的步骤,而不仅仅是
setText
電话,檢查Thread.currentThread().interrupted()
是一个好习惯 在每个步骤之間-如果設置了itnerrupt標志,則退出迴圈.這大致就是內建的阻塞方法(例如I / O)所做的,以便它们可以被其他執行緒中斷-因為running
標記仅在每个迴圈中檢查一次,如果每个迴圈需要20分钟,則對它进行設置没有多大好處。