How to create these three threads in Java

creating multiple threads in java
print 1 to 10 using thread in java
addition and subtraction using threads in java
creating threads in java
3 ways to create thread in java
threads in java w3schools
how to run two threads simultaneously in java
how to run multiple threads parallel in java

I am new to threads, and I don't know much about them, however I am struggling with creating them mainly.

I created a GUI program that repeatedly sorts a randomly generated array of ints using either selection sort, insertion sort, or merge sort. Each sort operates on a list whose size is raised by a power of 2. Upon completion of each sort, the number of elements sorted and the number of milliseconds it took is displayed.

I have 3 classes already done, they are Merge, selection, and insertion.

My Merge sort is working correctly, however I am still having trouble with the selection and insertion. I'm not sure if my 'if' and 'else' statements are incorrect, or if the threads themselves are wrong, but I am struggling with them.

Here's what I have in my Main class.

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();
 }
}

I am not too concerned with what's above. I am more concerned on how to create my thread in my SortRunnable class which these threads are created. Here is what is expected from this class.

This class contains the code used to time and execute the selected sort.

• You can find the difference between calls to System.currentTimeMillis() at the start end end of the sort to get its runtime.

• Call "Thread.yield()" in the Runnable before the search is executed to ensure that the GUI thread has the priority required to update its display as needed.

• When the sort has finished, the display should be updated in the GUI thread. This can be accomplished by calling the "displayResult" method on the Sorter reference. This call should occur within the Runnable object's run method, passed as an argument to SwingUtilities invokeLater method, as in:

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

Here is my code in there that I need help in.

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
            }
        });
    }

}

I just need help with the Insertion and Selection thread. Thank you! If you would like their individual classes so you can see what's inside of them let me know.

SwingUtilities.invokeLater places the request into in the Swing's event queue to be processed "at some point in the future". The Runnable is dequeued and executed within the context of the Event Dispatching Thread, meaning your sort is running in the same thread as the UI and will block it until it has completed.

Now, here is where things get really complicated. Swing is NOT thread safe (meaning you shouldn't update the UI from outside of the Event Dispatching Thread context)and is single threaded, meaning any long running or blocking operations will prevent the UI from been updated.

The "long" answer is, use a SwingWorker, which is designed for this job. However, you can continue using your code, but it's a little more messy.

You need to capture some more details, like when the sort was started and when the sort ended. You then need to calculate the difference between these two points in time as milliseconds.

There are lots of ways you "might" do this, but since Java now sports a nice new date/time API, you might as well start making use of it.

This information is then passed back to the UI, maybe something like...

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);
            }
        });
    }

}

Okay, the next problem, is you're not making use of the ExecutorService.

First, it really should be an instance field, as you don't need to keep creating more instances of it.

Second, your logic is all over the place, basically you want to...

  1. Create an instance of the Sorter
  2. Fill the array
  3. Create an instance of SortRunnable
  4. Submit SortRunnable to the ExecutorService so it can be executed...

Maybe something more like...

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);
    }

Java Thread Tutorial: Creating Threads and Multithreading in Java , The easiest way to create a thread is to create a class that implements the Runnable interface. To execute the run() method by a thread, pass an instance of MyClass to a Thread in its constructor (A constructor in Java is a block of code similar to a method that's called when an instance of an object is created). Extending Java Thread The second way to create a thread is to create a new class that extends Thread, then override the run() method and then to create an instance of that class. The run() method

My solution on creating these threads go as following:

In the sortRunnable class:

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
            }
        });
    }

That's where I created my threads.

On my other class, I put them in as following:

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();
        }
    }
}

Which the other methods was asked to do, but that's where I put in my threads.

Print sequence using 3 threads in java, Let's create a class named “PrintSequenceRunnable” which will implement the Runnable interface. Let's create a class named “PrintThreadsSequentiallyMain” which will implement the Runnable interface. When you run above program, you will get below output. That's all about printing threads using 3 threads in java. I am new to threads, and I don't know much about them, however I am struggling with creating them mainly. I created a GUI program that repeatedly sorts a randomly generated array of ints using ei

Thread sortContext = new Thread(new SortRunnable(*whatever args you need*));
sortContext.start();

should do the trick unless you try to update the ui from the new thread.

CHAPTER 6 --Threads and Multithreading in Java, Illustration 6.1 // Creating and running threads using Illustration 6.2 /* Creating three threads using the� Java’s multithreading system is built upon the Thread class, its methods, and its companion interface,  Runnable. To create a new thread, your program will either extend  Thread  or  implement  the  Runnableinterface. The Thread class defines several methods that help manage threads. The table below displays the same:

Java Thread | Multithreading In Java, Java Thread Tutorial: Creating Threads and Multithreading in Java This blog will introduce you to all the Java Thread concepts which many people 3. 4. 5. public class MyClass implements Runnable {. public void run(){. Threads are instances of class java.lang.Thread, or instances of subclasses of this class. In addition to being objects, java threads can also execute code. In this Java thread tutorial I will explain how to create and start threads. Java Threads Video Tutorial. In case you prefer video, here is a video version of this Java Threads tutorial

How to use Multiple Threads in Java, Btw, for the purpose of this tutorial and example, creating just three threads are enough. Let's assume we create threads T1, T2, and T3. While creating we pass � Printing numbers using 3 threads – Java program In the program each thread is assigned a number (0, 1 and 2 respectively). Before thread prints a number, each number is divided by 3 and the thread which has an assigned number equal to the remainder of this division is eligible to print the number.

Creating and Starting Java Threads, Create a Java Lambda that implements the Runnable interface. All three options are explained in the following sections. Java Class Implements� Thread Thread-2 exiting. Create a Thread by Extending a Thread Class. The second way to create a thread is to create a new class that extends Thread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class.

Comments
  • Poor title. Rewrite to summarize your specific technical issue.
  • @BasilBourque I have three classes that I didn't put on here, but they are the MergeSort, InsertionSort and SelectionSort. They do all the sorting. Yeah how do I make them each individually as threads.
  • Your title needs rewriting to show how this Question is distinct from the 29 million posts on Stack Overflow related to Java & threads.
  • Alright, sounds reasonable, um where did the endDate and startDate come from? did you mean endTime and startTime?
  • @AdanVivero Whoops, copy and pasting from multiple sources :P
  • Alright, also, I have the algorithm in a different class. I just don't know how to bring it over to my e.getSource. Also I have a sort button that is a JComboBox that has the three sort methods inside of it. Do you still recommend to have each of them have their own e.getsource? And what do I have it set eqaul to?
  • "I have the algorithm in a different class" - Assuming that their within the same class path when built and run, simply create a new instance when you need to. "Do you still recommend to have each of them have their own e.getsource?" - For simplicity, probably, but if I was doing it, I would wrap the instance of Sorter and it's name into a class and use a custom cell renderer to render the text, that way when the JComboBox's ActionListener is triggered, I'd just have to get a reference to the wrapper class, extract the details and pass them to the SortRunnable, but that's me
  • Alright, I figured it out. I have the Merge thread working. I updated my code up above and everything, I am just struggling with my Insertion and Selection sort threads.
  • Just one question, where exactly do I put this in? Like which class?
  • The OP is already using a ExecutorService, ExecutorService es = Executors.newSingleThreadExecutor();, all be it poorly
  • wherever you want to initiate one of your three sorts. I see you have a listener on a 'sort button' perhaps in that class somewhere in the method thats called when the event is fired
  • an ExecutorService is used for scheduling concurrent work on a single thread or thread pool. if this is what you are after than your question should be revised
  • docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html I think you'll want to have a firm grasp on terminology and basic object use before you try to wrap your head around parallel execution contexts. Please start with the link above