java - 当我尝试中断线程时 JFrame 卡住

标签 java multithreading swing jframe

我在这个练习中遇到了这个问题,我有 3 个类,一个 Provider(Thread),它不断提供存储在 LinkedList 中的整数产品。一旦尺寸至少达到 10,零售商(Thread)就可以全部购买。还有协调线程的分配器。 产品显示在 JFrame 上,然后当我单击“停止”按钮时,每个线程都会停止,每个零售商都会告诉他们购买了多少产品。

编辑:忘记提出问题,每次我单击“停止”按钮时,应用程序都会卡住,我什至无法关闭 JFrame 窗口,不明白为什么。

 public class Distributor {

    private JTextField textfield = new JTextField();
    private LinkedList<Integer> productList = new LinkedList<Integer>();
    private JFrame frame = new JFrame("Window");
    private JButton btn = new JButton("Stop");
    private Thread provider = new Thread(new Provider(this));
    private LinkedList<Thread> retailerList = new LinkedList<Thread>();

    private void addRetailer(int num) {
        for (int i = 0; i < num; i++)
            retailerList.add(new Thread(new Retailer(i, this)));
    }

    public Distributor() {
        frame.setSize(300, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.add(textfield);
        frame.add(btn, BorderLayout.SOUTH);
        addRetailer(2);


        btn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    provider.interrupt();
                    provider.join();
                    System.out.println(provider.isAlive());

                    for (Thread t : retailerList) {
                        t.interrupt();
                        t.join();
                        System.out.println(t.isAlive());
                    }
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        });
    }

    public void execute() {
        frame.setVisible(true);
        provider.start();
        for (Thread t : retailerList)
            t.start();
    }

    // Keeps providing products, and notifies retailers when there are 10 products
    public synchronized void provide(int product) {
        textfield.setText(productList.toString());
        productList.add(product);
        if (productList.size() == 10)
            notifyAll();
    }

    // Sells all the products if there are at least 10 to sell.
    public synchronized int sell() throws InterruptedException {
        while (productList.size() < 10)
            wait();

        int total = productList.size();
        notifyAll();
        textfield.setText(productList.toString());
        productList.clear();
        return total;
    }
}

提供者类:

public class Provider implements Runnable {
private Distributor distribuidor;
private int total = 0;

public Provider(Distributor distribuidor) {
    super();
    this.distribuidor = distribuidor;
}

@Override
public void run() {
    while (!Thread.interrupted()) {
        try {
            distribuidor.provide((int) (Math.random() * 10) + 1);
            Thread.sleep(10);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    System.out.println("Provider Interrupted");
 }
}

零售商类别:

public class Retailer implements Runnable {

private Distributor distributor;
private int total = 0;
private int id;

public Retailer(int id, Distributor distributor) {
    super();
    this.id = id;
    this.distributor = distributor;
}

@Override
public void run() {
    while (!Thread.interrupted()) {
        try {
            total += distributor.sell();
            Thread.sleep(10);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    System.out.println("Retailer id: " + id + " bought: " + total + " products");
 }
}

主类:

public class Main {
    public static void main(String[] args) {
        Distributor distributor = new Distributor();
        distributor.execute();
    }
}

最佳答案

不要在循环内捕获 InterruptedException,而是将循环放在 try { ... } 内

提供商类别:

public class Provider implements Runnable {

    private Distributor distribuidor;
    private int total = 0;

    public Provider(Distributor distribuidor) {
        super();
        this.distribuidor = distribuidor;
    }

    @Override
    public void run() {
        try {
            while (!Thread.currentThread().isInterrupted()) {
                distribuidor.provide((int) (Math.random() * 10) + 1);
                Thread.sleep(10);
            }
        } catch (InterruptedException interruptedException) {
        }
        System.out.println("Provider Interrupted");
    }
}

零售商类别:

public class Retailer implements Runnable {

    private Distributor distributor;
    private int total = 0;
    private int id;

    public Retailer(int id, Distributor distributor) {
        super();
        this.id = id;
        this.distributor = distributor;
    }

    @Override
    public void run() {
        try {
            while (!Thread.currentThread().isInterrupted()) {
                total += distributor.sell();
                Thread.sleep(10);
            }
        } catch (InterruptedException interruptedException) {
        }
        System.out.println("Retailer id: " + id + " bought: " + total + " products");
    }
}

关于java - 当我尝试中断线程时 JFrame 卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33707922/

相关文章:

java - 不允许使用 CleartextTraffic 和 NetworkSecurityConfig

java - 指定应考虑进行不同计算的列

c - 使用 pthread 让一个线程执行其他线程发送的所有磁盘写入操作?

ruby - 重用 Ruby 中线程之间的连接/替换 Net::HTTP::Persistent

java - 为什么在 boolean 值上同步不是一个好习惯?

java - 将不同对象类型的数组列表合并为一个

java - 用于同步的 CyclicBarrier 与 CountDownLatch

java - 如何在 Java 中将 boolean 数组转换为二进制数组,反之亦然?

java - 如何从图像文件中读取文本

java - 动态 JPanel 调整大小问题