스레드를 공부하고 응용해보기 위해 라면 타이머를 만들어 보았다.
동시에 라면 세개를 끓일 때 사용할 수 있는 라면 타이머로 라면 타이머는 각자 돌아가므로 스레드를 이용해야 한다.
실행하면
이런 식으로 각자 돌아가고 시작을 누르면
이렇게 다시 돌아가는데
이 때 실행중이던 스레드를 종료하는게 오히려 가장 힘들었다 ㅎㅎ....
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Timer extends JFrame {
public Timer()
{
setTitle("라면 타이머");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout());
JTextField t1 = new JTextField("3 : 00");
t1.setPreferredSize(new Dimension(80, 50));
JTextField t2 = new JTextField("3 : 00");
t2.setPreferredSize(new Dimension(80, 50));
JTextField t3 = new JTextField("3 : 00");
t3.setPreferredSize(new Dimension(80, 50));
c.add(t1);
c.add(t2);
c.add(t3);
JButton b1 = new JButton("시작");
JButton b2 = new JButton("시작");
JButton b3 = new JButton("시작");
c.add(b1);
c.add(b2);
c.add(b3);
class MyActionListener implements ActionListener
{
Thread nowRunning = null;
public void actionPerformed(ActionEvent e) {
JButton b = (JButton)(e.getSource());
class TIME implements Runnable
{
JTextField t;
public TIME(JTextField t)
{
this.t = t;
}
public void run() {
for(int i = 180; i >= 0; i--)
{
int min = i /60;
int second1 = (i % 60) / 10;
int second2 = i % 10;
t.setText(min + " : " + second1 + second2);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
break; // interruptedException이 발생함을 이용해서 종료하는 것이 interrupt메소드의 역할이므로 break 시켜줘야함
}
}
}
}
if(b.equals(b1))
{
Thread TiME = new Thread(new TIME(t1));
if(nowRunning != null)
{
if(!nowRunning.isInterrupted())
{
nowRunning.interrupt();
}
nowRunning = TiME;
}
else nowRunning = TiME;
TiME.start();
}
else if(b.equals(b2))
{
Thread TiME = new Thread(new TIME(t2));
if(nowRunning != null)
{
if(!nowRunning.isInterrupted())
{
nowRunning.interrupt();
}
nowRunning = TiME;
}
else nowRunning = TiME;
TiME.start();
}
else if(b.equals(b3))
{
Thread TiME = new Thread(new TIME(t3));
if(nowRunning != null)
{
if(!nowRunning.isInterrupted())
{
nowRunning.interrupt();
}
nowRunning = TiME;
}
else nowRunning = TiME;
TiME.start();
}
else
{
System.out.println("지정하지 않은 행동입니다.");
}
}
}
b1.addActionListener(new MyActionListener());
b2.addActionListener(new MyActionListener());
b3.addActionListener(new MyActionListener());
setVisible(true);
}
public static void main(String[] args) {
new Timer();
}
}
배운 점
스레드의 활용
setSize() 와 setPreferredSize()
interrupt() 메소드를 통해 interruptException() 이용하여 스레드 종료하기