スレッドの起動停止を制御する
戻る
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
/**
$Id: threadcontroller.html,v 1.1 2009/06/22 16:12:30 kishi Exp kishi $
@author KISHI Yasuhiro
*/
public class DrawingController implements Runnable {
private int i = 0;
private boolean runningStatus;
private JButton statusButton;
public DrawingController( JButton statusButton ) {
runningStatus = true;
this.statusButton = statusButton;
}
public void run() {
while ( runningStatus ) {
i++;
System.out.println( "i=" + i );
statusButton.setText( new Integer( i ).toString() );
try {
Thread.sleep( 500 );
} catch ( Exception exception ) {
exception.printStackTrace();
}
}
}
public void setRunningStatus( boolean runningStatus ) {
this.runningStatus = runningStatus;
}
}
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
/**
<pre>
$Id: threadcontroller.html,v 1.1 2009/06/22 16:12:30 kishi Exp kishi $
Theadの開始・停止をコントロールする
</pre>
@author KISHI Yasuhiro
*/
public class ThreadController extends JFrame implements ActionListener {
JButton startButton = new JButton( "Start" );
JButton stopButton = new JButton( "End" );
JButton statusButton = new JButton( "STATUS" );
JPanel northPanel;
JPanel southPanel;
DrawingController dc;
Thread myThread;
public static void main( String args[] ) {
new ThreadController().setVisible( true );
}
public ThreadController() {
setTitle( "Theadの開始・停止をコントロールする" );
setDefaultCloseOperation( EXIT_ON_CLOSE );
northPanel = new JPanel();
// 開始ボタンを追加
northPanel.add( startButton );
startButton.addActionListener( this );
startButton.setActionCommand( "start" );
// 終了ボタンを追加
northPanel.add( stopButton );
stopButton.addActionListener( this );
stopButton.setActionCommand( "stop" );
southPanel = new JPanel();
southPanel.add( statusButton );
Container container = getContentPane();
container.add( northPanel, BorderLayout.NORTH );
container.add( southPanel, BorderLayout.SOUTH );
setBounds( 10, 10, 300, 600 );
pack();
}
public void actionPerformed( ActionEvent e ) {
String action = e.getActionCommand();
if ( action.equals( "start" ) ) {
if ( dc == null ) {
statusButton.setText( "alive" );
System.out.println( "開始されました!" );
dc = new DrawingController( statusButton );
myThread = new Thread( dc );
// スレッド開始
myThread.start();
}
}
if ( action.equals( "stop" ) ) {
if ( dc != null ) {
System.out.println( "終了いたしました!" );
// スレッドを停止させるためにステータスをfalseにする
// Thread.stop()は推奨されないので使わない!
dc.setRunningStatus( false );
dc = null; // 明示的な開放
statusButton.setText( "sleeping" );
}
}
}
}
戻る