4: Java: Console Application with Multithreading and Timers

One user wanted to get a Tutorial wich describes Console App and Multithreading. For this we need to consider first how a console App works:

Starting, loading classes, executing commands and ends.

That means that, if we want to have an App which is running continous we also need to have a Loop for the App. Let’s look on this loop as the central event Loop of the App. Here all stuffs are controlled and the Loop shall end when something was changed like the status of a Boolean or the size of an array or what ever.

If we do not have something like that, the command line App would end immediately.

For our Tutorial App I start like in Tutorial one with a Netbeans Ant Java Project,


let’s give it the name Cltest. We generate it with checked “generate Main”.
We click on Finish and have a Project with a ready generated Main class. This project itself is not doing anything but it can already run:

Now we need to invoke the Stuffs we want to have. At first we need a Thread Class, wie call the class test thread and adding the class to our cltest package:

In the Test Class we invoke extends Thread like shown here:

For demonstration I will insert the thread which is counting up a number and a timer which reads the integer every second. The thread itself counts to one million and adds one to the integer. So the main class gets the variable:
public static int i =0;
and the Thread the counting Job:

Now we need the Timer in the main class, we use a Swing timer what would anyhow mostly be used while mostly we need that for actualizing the GUI so:

Important: The IDE will mark the line with the timer command red: you need to import the timer for it. Import the Swing Timer Library!

Now we need in the Thread class also a loop. Why? While the thread would end like a command line program when only having a few commands. The thread ends if there is no loop. For example like this:


Here you can see that in the run() method of the thread we have a Loop while(true) which makes the thread continuous working.

The same problem we had also in our main method, remember, the main method looks so:

public static void main(String args) {

    cltest.Testthread newtestthread = new cltest.Testthread();
    newtestthread.start();
    swingtimer.start();
    
    while(i<10000){
        
        
        
    }
    // TODO code application logic here
}

I could do also a while(true) loop but here I wanted the program somewhen to end when reaching the number of counts.

So we learned today to build a thread class (extends thread with a run() method) and how to use a timer to display what the thread class is doing, While Swing is not thread safe I recommend for all GUI implementations of thread relevant data to use timers to display. That is similar with Xojo where you use timers for GUI actions from threads. Have fun.

2 Likes