24 Sept 2012

how to interrupt in java

/* how to interrupt in java */

public class TestHello 
{
    private static HelloTask task;
    public static void main(String[] args) 

    {
        java.lang.Thread thread = new 
java.lang.Thread((task = new HelloTask()));
        thread.setDaemon(true);
        thread.start();

        
java.awt.JFrame frame = new java.awt.JFrame();
        frame.setDefaultCloseOperation(java.awt.JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new GridBagLayout());
        frame.setSize(200, 200);
        frame.setLocationRelativeTo(null);

        
java.awt.JButton goButton = new java.awt.JButton("Go");
        java.awt.JButton stopButton = new java.awt.JButton("Stop");

        goButton.setActionCommand("Go");
        stopButton.setActionCommand("Stop");

        ActionHandler handler = new ActionHandler();

        goButton.addActionListener(handler);
        stopButton.addActionListener(handler);

        frame.add(goButton);
        frame.add(stopButton);

        frame.setVisible(true);

    }

    public static class ActionHandler implements ActionListener 

    {
        public void actionPerformed(ActionEvent e) 

        {

            if (e.getActionCommand().equals("Go")) 

            {
                task.start();
            } 

            else if (e.getActionCommand().equals("Stop")) 
            {
                task.pause();
            }

        }

    }

    public static class HelloTask implements 
java.lang.Runnable 
    {
        private static final Object WAIT_LOCK = new Object();
        private boolean dump = false;

        public void start() 

        {
            synchronized (WAIT_LOCK) 

            {
                dump = true;
                WAIT_LOCK.notify();
            }
        }

        public void pause() 

        {
            synchronized (WAIT_LOCK) 

           {
                dump = false;
                WAIT_LOCK.notify();
            }
        }

        public void run() 

        {
            while (true) 

             {
                while (dump) 

                {
                    System.out.println("Hello");
                }
                try 

               {
                    synchronized (WAIT_LOCK) 

                    {
                        WAIT_LOCK.wait();
                    }
                } 

                catch (java.lang.Exception e) 
                {
                }
            }
        }
    }
}

0 comments:

Post a Comment