정리노트

[자바/java] Thread. interrupt()로 컨트롤 본문

프로그래밍/Java

[자바/java] Thread. interrupt()로 컨트롤

Rolen 2023. 2. 3. 19:06

STOP 버튼을 눌러 카운트가 중단됨(thread 중단)

하나의 스레드가 다른 스레드의 interrupt()를 호출하면 해당 스레드는 중지된다.

이는 InterruptedException 로 예외처리를 하면 된다.

package threadControl;
import javax.swing.*;
import java.awt.*;

public class ThreadControl extends JFrame {
	private JLabel label;
	Thread t;
	
	class Counter extends Thread {
		public void run() {
			for (int i = 1; i <= 10; i++) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					return ; // return을 해야 중단
				}
				label.setText(i + "");
			}
		}
	}
	
	public ThreadControl() {
		setTitle("카운트");
		setSize(400, 150);
		
		getContentPane().setLayout(null);	// 이벤트 처리가 있어 pane 사용 / panel(x)
		label = new JLabel("0");
		label.setBounds(0, 0, 280, 100);
		label.setFont(new Font("Serif", Font.BOLD, 110));
		getContentPane().add(label);
		
		JButton button = new JButton("STOP");
		button.setBounds(247, 25, 125, 23);
		button.addActionListener(e -> t.interrupt()); // 버튼이 눌리면 interrupt() 실행 // 람다
		getContentPane().add(button);
		
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		t = new Counter();
		t.start();
	}

	public static void main(String[] args) {
		ThreadControl t = new ThreadControl();
	}

}
728x90