希望使用thread.sleep暂停线程

时间:2015-06-22 21:53:05

标签: java multithreading

我正在使用鼠标监听器来按下并释放鼠标。当按下鼠标时,我希望有一个计数器递增一个变量,当鼠标被释放时,我想减少该变量。现在,我的代码正在工作并且这样做但是增量太快我想减速它因为我在游戏中使用这些数字作为坐标。我尝试添加一个Thread.sleep(100),但我得到了偏斜的输出。看起来好像有多个线程同时出现,我到处都有数字。下面是示例代码。

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.*;
import java.awt.event.ActionListener;
import java.lang.*;

public class Sample extends JFrame {
    private JPanel jp = new JPanel();

    int i = 0;
    boolean once = true;
    boolean on = true;

    Thread t1 = new Thread(new Increase());
    Thread t2 = new Thread(new Decrease());

    public sample() {
        setVisible(true);
        setSize(300, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        add(jp);

        addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent event) {
                if (!once) //false
                {
                    t2.interrupt();
                }

                if (once) //true
                {
                    once = false;
                    t1.start();
                }
                else {
                    t1 = new Thread(new Increase());
                    t1.start();
                }
            }

            public void mouseReleased(MouseEvent event) {
                t1.interrupt();
                if (on) //true
                {
                    on = false;
                    t2.start();
                }
                else {
                    t2 = new Thread(new Decrease());
                    t2.start();
                }
            }
        });
    }

    public static void main(String[] args) {
        new Sample();
    }

    public int getI() {
        return i;
    }

    public void setI(int num) {
        i = num;
    }

    class Increase implements Runnable {
        public void run() {
            int num = getI();
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    setI(++num);
                    Thread.sleep(100);
                    System.out.println(num);
                }
                catch (InterruptedException e) {
                }
            }
        }
    }

    //Thread.currentThread().isInterrupted()
    class Decrease implements Runnable {
        public void run() {
            int num = getI();
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    setI(--num);
                    Thread.sleep(100);
                    System.out.println(num);
                }
                catch (InterruptedException e) {
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:5)

你可能在两个线程之间遇到竞争状态,i不易变的事实也表明线程可能没有使用相同的实际值。

线程也是不可重入的,这意味着一旦存在run方法,它们就无法重新启动。

只需使用单个Thread和“delta”(或更改)值即可获得相同的结果。

以下示例使用Swing Timer,因为它更简单并且允许我安全地更新UI,但原理是相同的。

Counter

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JLabel label;
        private Timer timer;
        private int value = 0;
        private int delta = 1;

        public TestPane() {
            setLayout(new GridBagLayout());
            label = new JLabel("0");
            add(label);
            addMouseListener(new MouseAdapter() {

                @Override
                public void mousePressed(MouseEvent e) {
                    delta *= -1;
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    delta *= -1;
                }

            });

            timer = new Timer(100, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    setValue(getValue() + delta);
                }
            });
            timer.start();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        public int getValue() {
            return value;
        }

        public void setValue(int value) {
            this.value = value;
            label.setText(Integer.toString(value));
        }

    }

}

更新了双“线程”

只是因为我完全疯了,很高兴能够展示额外的工作量。此示例使用两个Thread s。

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel implements Value {

        private JLabel label;
        private volatile int value = 0;

        private ManipulateRunner incrementRunner;
        private ManipulateRunner decrementRunner;

        private Thread incrementThread;
        private Thread decrementThread;

        public TestPane() {

            incrementRunner = new ManipulateRunner(this, 1);
            decrementRunner = new ManipulateRunner(this, -1);

            setLayout(new GridBagLayout());
            label = new JLabel("0");
            add(label);
            addMouseListener(new MouseAdapter() {

                @Override
                public void mousePressed(MouseEvent e) {

                    decrementRunner.pause();
                    if (incrementThread == null) {
                        incrementThread = new Thread(incrementRunner);
                        incrementThread.start();
                    }

                    incrementRunner.resume();

                }

                @Override
                public void mouseReleased(MouseEvent e) {

                    incrementRunner.pause();
                    if (decrementThread == null) {
                        decrementThread = new Thread(decrementRunner);
                        decrementThread.start();
                    }

                    decrementRunner.resume();

                }

            });
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        public int getValue() {
            return value;
        }

        @Override
        public void setValue(final int value) {
            if (EventQueue.isDispatchThread()) {
                this.value = value;
                label.setText(Integer.toString(value));
            } else {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        setValue(value);
                    }
                });
            }
        }

    }

    public static interface Value {

        public int getValue();

        public void setValue(int value);
    }

    public static class ManipulateRunner implements Runnable {

        protected final Object pauseLock = new Object();
        private int delta;
        private AtomicBoolean paused = new AtomicBoolean(false);
        private AtomicBoolean stopped = new AtomicBoolean(false);
        private Value value;

        public ManipulateRunner(Value value, int delta) {
            this.delta = delta;
            this.value = value;
        }

        public void pause() {

            if (!paused.get() && !stopped.get()) {

                paused.set(true);
                synchronized (pauseLock) {
                    pauseLock.notify();
                }

            }

        }

        public void resume() {

            if (paused.get() && !stopped.get()) {

                paused.set(false);
                synchronized (pauseLock) {
                    pauseLock.notify();
                }

            }

        }

        public void stop() {

            if (!stopped.get()) {

                stopped.set(true);
                synchronized (pauseLock) {
                    pauseLock.notify();
                }

            }

        }

        @Override
        public void run() {

            while (!stopped.get()) {

                while (!stopped.get() && paused.get()) {
                    synchronized (pauseLock) {
                        try {
                            pauseLock.wait();
                        } catch (InterruptedException ex) {
                        }
                    }
                }

                if (!stopped.get()) {
                    value.setValue(value.getValue() + delta);

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                    }
                }

            }

        }

    }

}

就个人而言,最简单且最有效的解决方案是更好的解决方案,但那就是我