【问题标题】:How to create these three threads in Java如何在Java中创建这三个线程
【发布时间】:2019-04-15 23:29:52
【问题描述】:

我是线程的新手,我对它们了解不多,但是我主要是在努力创建它们。

我创建了一个 GUI 程序,它使用选择排序、插入排序或合并排序对随机生成的整数数组进行重复排序。每次排序都对一个列表进行操作,该列表的大小是 2 的幂。每次排序完成后,将显示已排序的元素数和所用的毫秒数。

我已经完成了 3 个类,它们是合并、选择和插入。

我的合并排序工作正常,但是在选择和插入时我仍然遇到问题。我不确定我的“if”和“else”语句是否不正确,或者线程本身是否错误,但我正在努力解决它们。

这是我在主课上的内容。

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class Sorter extends JFrame
{
private static final long serialVersionUID = 1L;
private static final int WIDTH = 400;
private static final int HEIGHT = 300;

public static final String SELECTION_SORT_TEXT = "Selection Sort";
public static final String INSERTION_SORT_TEXT = "Insertion Sort";
public static final String MERGE_SORT_TEXT = "Merge Sort";

private JComboBox sortingAlgorithms;
private JTextArea display;
private JButton sortButton;
private JPanel panel;
private JLabel loadingIcon;
private JLabel sort;
private String[] options = {SELECTION_SORT_TEXT, INSERTION_SORT_TEXT, MERGE_SORT_TEXT};

public Sorter()
{
    setTitle("Sorter");
    setSize(WIDTH, HEIGHT);
    setLayout(new BorderLayout());
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    createContents();
    setVisible(true);
}
private void createContents()
{
    //TODO: Implement

    this.panel = new JPanel(new FlowLayout());
    this.display = new JTextArea();
    this.loadingIcon = new JLabel(new ImageIcon("loading.gif"));
    this.sort = new JLabel("Sorting Algorithm");
    this.sortButton = new JButton("Sort");
    this.sortingAlgorithms = new JComboBox<>(options);
    loadingIcon.setSize(25,25);

    display.setBorder(new EmptyBorder(10,10,10,10));

    panel.add(sort);
    panel.add(sortingAlgorithms);
    panel.add(sortButton);
    panel.add(loadingIcon);

    sortButton.addActionListener(new SortButtonListener());

    loadingIcon.setVisible(false);
    display.setEnabled(false);

    setLayout(new BorderLayout());
    add(panel, BorderLayout.NORTH);
    add(display, BorderLayout.CENTER);
}

private class SortButtonListener implements ActionListener
{
    private int[] arr;
    private SortRunnable sr;

    public void actionPerformed(ActionEvent e)
    {
        sr.run();
        ExecutorService es = Executors.newSingleThreadExecutor();
        //TODO: Finish Implementation
        if(e.getSource() == sortButton)
        {
            sortingAlgorithms.setEnabled(false);
            sortButton.setEnabled(false);
            loadingIcon.setVisible(true);
            display.setText("N\t\tRuntime (ms)");             
        }
        arr = new int [2000];
        for(int i = 0; i <= 8; i++)
        {
            arr = new int [(int) Math.pow(2, i) * 1000];
            fillArr();
            sr = new SortRunnable((String) sortingAlgorithms.getSelectedItem(), arr, Sorter.this);
            es.execute(sr);
        }
        Thread sortContext = new Thread(new SortRunnable((String) 
        sortingAlgorithms.getSelectedItem(), arr, Sorter.this));
        sortContext.start();
        es.shutdown();
    }
    /*
    These values are powers of 2 from 0 to 8, times 1000.
     */
    private void fillArr()
    {
        Random r = new Random();
        int n = 0;
        for(int i=0; i<arr.length; ++i)
        {
            arr[i] = r.nextInt();
        }
    }
}
/*
The displayResult method is responsible for adding the provided sort runtime information to
the display. It should also check to see if the final sort runtime information is present. If so,
it should hide the loading gif and enable the JComboBox and sort button.
 */
public synchronized void displayResult(int n, long runtime)
{
    //TODO: Implement
    display.append("\n" + n + "\t\t" + runtime);
}

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

我不太关心上面的内容。我更关心如何在创建这些线程的 SortRunnable 类中创建我的线程。这是对这门课的期望。

此类包含用于计时和执行所选排序的代码。

• 您可以在排序的开始和结束时找到对 System.currentTimeMillis() 的调用之间的区别,以获取其运行时间。

• 在执行搜索之前调用 Runnable 中的“Thread.yield()”,以确保 GUI 线程具有根据需要更新其显示所需的优先级。

• 排序完成后,应在 GUI 线程中更新显示。这可以通过在 Sorter 引用上调用“displayResult”方法来完成。此调用应发生在 Runnable 对象的 run 方法中,作为参数传递给 SwingUtilities invokeLater 方法,如下所示:

 SwingUtilities.invokeLater(new Runnable() 
 {
 @Override
 public void run() 
 {
   //call Sorter's displayResult method here
 }
 });

这是我需要帮助的代码。

import javax.swing.*;

public class SortRunnable implements Runnable
{

    private String sortingAlgorithm;
    private int[] arr;
    private Sorter sorter;

    public SortRunnable(String sortingAlgorithm, int[] arr, Sorter sorter)
    {
        this.sortingAlgorithm = sortingAlgorithm;
        this.arr = arr;
        this.sorter = sorter;
    }
    @Override
    public void run()
    {
        Thread.yield();
        if(sortingAlgorithm.equals(sorter.MERGE_SORT_TEXT))
        {
            MergeSort.mergeSort(arr);
        }
        Thread.yield();
        if(sortingAlgorithm.equals(sorter.SELECTION_SORT_TEXT))
        {
            SelectionSort.sort(arr);
        }
        Thread.yield();
        if(sortingAlgorithm.equals(sorter.INSERTION_SORT_TEXT))
        {
            InsertionSort.sort(arr);
        }
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                Thread.yield();
                sorter.displayResult(arr.length, System.currentTimeMillis());
            //call Sorter's displayResult method here
            }
        });
    }

}

我只需要插入和选择线程的帮助。谢谢!如果您想要他们的个人课程,以便您可以看到其中的内容,请告诉我。

【问题讨论】:

  • 糟糕的标题。重写以总结您的具体技术问题。
  • @BasilBourque 我这里没有放三个类,但它们是 MergeSort、InsertionSort 和 SelectionSort。他们做所有的排序。是的,我如何将它们分别作为线程。
  • 您的标题需要重写以显示此问题与29 million posts on Stack Overflow related to Java & threads 有何不同

标签: java user-interface executorservice execution java-threads


【解决方案1】:

SwingUtilities.invokeLater 将请求放入 Swing 的事件队列中,以便“在未来的某个时间点”进行处理。 Runnable 被出列并在 Event Dispatching Thread 的上下文中执行,这意味着您的排序在与 UI 相同的线程中运行,并将阻塞它直到它完成。

现在,事情变得非常复杂。 Swing 不是线程安全的(这意味着您不应该从 Event Dispatching Thread 上下文之外更新 UI)并且是单线程的,这意味着任何长时间运行或阻塞的操作都会阻止 UI 更新。

“长”的答案是,使用专为这项工作设计的SwingWorker。但是,您可以继续使用您的代码,但它会有点混乱。

您需要捕获更多详细信息,例如排序开始时间和排序结束时间。然后您需要以毫秒为单位计算这两个时间点之间的差异。

您“可能”有很多方法可以做到这一点,但由于 Java 现在提供了一个不错的新日期/时间 API,您不妨开始使用它。

这些信息随后被传回 UI,可能类似于...

public class SortRunnable implements Runnable
{

    private String sortingAlgorithm;
    private int[] arr;
    private Sorter sorter;

    public SortRunnable(String sortingAlgorithm, int[] arr, Sorter sorter)
    {
        this.sortingAlgorithm = sortingAlgorithm;
        this.arr = arr;
        this.sorter = sorter;
    }
    @Override
    public void run()
    {
        LocalDateTime startTime = LocalDateTime.now();
        MergeSort.mergeSort(arr);
        LocalDateTime endTime = LocalDateTime.now();
        long diff = ChronoUnit.MILLIS.between(startTime, endTime)
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                sorter.displayResult(arr.length, diff);
            }
        });
    }

}

好的,下一个问题是你没有使用ExecutorService

首先,它确实应该是一个实例字段,因为您不需要继续创建它的更多实例。

其次,你的逻辑到处都是,基本上你想......

  1. 创建Sorter 的实例
  2. 填充数组
  3. 创建SortRunnable 的实例
  4. SortRunnable 提交给ExecutorService 以便执行...

也许更像...

private ExecutorService es = Executors.newSingleThreadExecutor();
public void actionPerformed(ActionEvent e)
{
    fillArr();
    Sorter sorter = null;
    String algorthim = null;
    if(e.getSource() == options[0])
    {
        // create the instance of Sorter to be used...
        sorter = ...
        algorthim = ...
    }
    if(e.getSource() == options[1])
    {
        // create the instance of Sorter to be used...
        sorter = ...
        algorthim = ...
    }
    if(e.getSource() == options[2])
    {
        // create the instance of Sorter to be used...
        sorter = ...
        algorthim = ...
    }
    if (sorter != null) {
        SortRunnable sr = new SortRunnable(algorthim, arr, sorter)
        es.submit(sr);
    }

【讨论】:

  • 好吧,听起来有道理,嗯 endDate 和 startDate 是从哪里来的?你是说 endTime 和 startTime 吗?
  • @AdanVivero 哎呀,从多个来源复制和粘贴:P
  • 好吧,另外,我在不同的类中有算法。我只是不知道如何将它带到我的 e.getSource 中。我还有一个排序按钮,它是一个 JComboBox,里面有三种排序方法。您仍然建议让他们每个人都有自己的 e.getsource 吗?我将它设置为 eqaul 是什么?
  • “我在不同的类中有算法” - 假设它们在构建和运行时在同一个类路径中,只需在需要时创建一个新实例。 “你仍然建议让他们每个人都有自己的 e.getsource 吗?” - 可能为了简单起见,但如果我这样做,我会包装 Sorter 的实例及其名称进入一个类并使用自定义单元格渲染器来渲染文本,这样当JComboBoxActionListener 被触发时,我只需要获取对包装类的引用,提取详细信息并将它们传递给SortRunnable,但那是我
  • 好吧,我想通了。我有合并线程工作。我更新了上面的代码和所有内容,我只是在为我的插入和选择排序线程而苦苦挣扎。
【解决方案2】:

我创建这些线程的解决方案如下:

在 sortRunnable 类中:

public void run()
    {
        long store = System.currentTimeMillis();
        if(sortingAlgorithm.equals(sorter.MERGE_SORT_TEXT))
        {
            MergeSort.mergeSort(arr);
        }
        if(sortingAlgorithm.equals(sorter.SELECTION_SORT_TEXT))
        {
            SelectionSort.sort(arr);
        }
        if(sortingAlgorithm.equals(sorter.INSERTION_SORT_TEXT))
        {
            InsertionSort.sort(arr);
        }
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                sorter.displayResult(arr.length, System.currentTimeMillis()-store);
            //call Sorter's displayResult method here
            }
        });
    }

那是我创建线程的地方。

在我的另一堂课上,我把它们放在下面:

private class SortButtonListener implements ActionListener
{
    private int[] arr;
    private SortRunnable sr;

    public void actionPerformed(ActionEvent e)
    {
        ExecutorService es = Executors.newSingleThreadExecutor();
        //TODO: Finish Implementation
        if(e.getSource() == sortButton)
        {
            sortingAlgorithms.setEnabled(false);
            sortButton.setEnabled(false);
            loadingIcon.setVisible(true);
            display.setText("N\t\tRuntime (ms)");
        }
        arr = new int [2000];
        for(int i = 0; i <= 8; i++)
        {
            arr = new int [(int) Math.pow(2, i) * 1000];
            fillArr();
            sr = new SortRunnable((String) sortingAlgorithms.getSelectedItem(), arr, Sorter.this);
            es.execute(sr);
        }
        es.shutdown();
    }
    private void fillArr()
    {
        Random r = new Random();
        for(int i=0; i<arr.length; ++i)
        {
            arr[i] = r.nextInt();
        }
    }
}

要求其他方法执行哪些操作,但这就是我放入线程的地方。

【讨论】:

    【解决方案3】:
    Thread sortContext = new Thread(new SortRunnable(*whatever args you need*));
    sortContext.start();
    

    除非您尝试从新线程更新用户界面,否则应该可以解决问题。

    【讨论】:

    • 只有一个问题,我到底要把它放在哪里?喜欢哪一门课?
    • OP 已经在使用ExecutorServiceExecutorService es = Executors.newSingleThreadExecutor();,尽管效果不佳
    • 无论您想在哪里启动您的三种类型中的一种。我看到您在“排序按钮”上有一个侦听器,可能在事件触发时调用的方法中的某个类中
    • 一个 ExecutorService 用于在单个线程或线程池上调度并发工作。如果这是你所追求的,那么你的问题应该被修改
    • docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html 我认为在您尝试围绕并行执行上下文进行思考之前,您需要牢牢掌握术语和基本对象使用。请从上面的链接开始
    猜你喜欢
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-30
    • 2021-12-18
    • 2012-07-04
    • 1970-01-01
    相关资源
    最近更新 更多