How to write multi-threaded code in Java?

Posted on 2013-10-01
Medium Priority
Last Modified: 2013-10-15
I am writing a Java code and in this code, I call an external command by using cmd.exe and I run a batch file. Everything works fine up to this point. However, this is a UI application and after it calls the external command, the UI just waits for the other process to be completed and it you cannot click on any other button in the UI because it is just unresponsive.

As I talk to my colleagues, they recommended me to do multi-threading to solve this problem. Basically, I need to create another thread and then I need to run the external command in this thread. As a result I will be able to use the UI during the time the newly created thread is busy. This way I will use the UI and by using the stop button I will be able to stop this process at any time want.

However, I have never done anything about multi-threading until now and I am in a time pressure. I need to know how to create a new thread and do some processes in this thread.

Can you please help me how I should do this?
Question by:Tolgar
LVL 11

Accepted Solution

MajorBigDeal earned 500 total points
ID: 39538779
Debugging multi-threaded code can be difficult and time-consuming and it does not sound like it is necessary for the problem you have described.   How are you calling cmd.exe? Are you using Runtime.getRuntime().exec?  If so it should not stop and wait for the command to complete unless you have also specified waitFor().  If so, remove the waitFor() and your problem is solved.  

Here is a better explanation:


Author Comment

ID: 39538813
I use Runtime.getRuntime().exec and this is the code that I run this external command and even though I don't use waitFor() the code just halts until the process is finished.

Can you please take a look at the code that I have? Could there be a problem/bug at line 22 where I have the while loop?

                    tempDir = "C:/Temp/mgcheck";
                    setMgcheckPathCmd = "cmd.exe /C mg.bat -using A 
                    batchFileCmd = "cmd.exe /C \\\\somePath\\mgcheckGui.bat" +" " + Location + " " + fileInfoLine + " " + checkList ;
                perlCmd = batchFileCmd;
                Runtime mgcheck_runtime = Runtime.getRuntime();
                try {
                    mgcheck_process = mgcheck_runtime.exec(perlCmd, environment);
                } catch (Exception e) {
                    System.out.println("error executing " + perlCmd);
                /* dump output stream */
                InputStream is = mgcheck_process.getInputStream();
                BufferedReader reader = new BufferedReader
                    ( new InputStreamReader(is));
                String commandLineOutput;
                String resultsXML = null;
                while ((commandLineOutput = reader.readLine()) != null) {
                    Pattern p = Pattern.compile("\\d{8}_\\d{4}_\\d{2}_Mgcheck.xml");
                    Matcher m = p.matcher(commandLineOutput);
                    if (m.find()){
                        resultsXML = m.group();                       

Open in new window

LVL 17

Assisted Solution

krakatoa earned 500 total points
ID: 39539174
If you want to run a lengthy task then as you rightly say, it is best done on a separate thread. You can instantiate, and run(), a(n) (inner) Runnable-implementing class to do this. Then at the point where you need to make use of it, call it and pass the parameters required. From your above code, it looks like you are calling your process inline at the moment.
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

LVL 86

Expert Comment

ID: 39539283
LVL 17

Expert Comment

ID: 39541680
Simplified dem, but this shows how a task can run and leave the GUI buttons operational. Hope it helps. Obviously.

import javax.swing.*;
import java.awt.*;
import java.net.*;
import java.util.*;
import java.awt.event.*;

class Asynch extends JFrame implements ActionListener{

static JButton j,jst;
static Asynch a;
static volatile boolean taskunderway = false;
static int times = 1;

  public static void main(String[] args){

	a = new Asynch();

	j = new JButton("Click to start task");

	jst = new JButton("Click to stop task");

	a.setLayout(new BorderLayout());


	a.setSize(new Dimension(350,100));




 static class Task implements Runnable{

	public void run(){

		}catch(Exception e2){}

		j.setText(" . . . running . . . ");
		while((taskunderway&&a.isVisible())){System.out.println(new Date());}	
		System.out.println("Task ended.");	
		times = 1;	


  public void actionPerformed(ActionEvent e){

		if(((JButton)e.getSource()).getText().equals("Click to stop task")&&taskunderway){
			taskunderway = false;
			System.out.println("Stopping task");
			j.setText("Click to start task");

		if(((JButton)e.getSource()).getText().equals("Click to stop task")&&!taskunderway){return;}
		  Thread th = null;	
		  th = (new Thread(new Task()));
		else{j.setText("Said I'm running "+(times++)+" times now!");/*try{
		}catch(Exception e2){}j.setText(" . . . running . . . ");*/}


Open in new window


Author Comment

ID: 39542019
@krakatoa: can you please show me how I can implement it in the code that I posted above.

LVL 17

Expert Comment

ID: 39542531
The idea of my example was how a task from the main thread can be delegated to a separate process, that's all. I thought you were looking for how to approach multi-threaded code.

I am not going to implement it in your code, sorry.

Otoh, there's more reason to adopt CEHJ's proposal, since what I've tried to illustrate is almost certainly not as OOP-PC as Swingworker, and his expert opinion is always to be favoured in this TA.

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
AngularJS web development a very simple procedure. So, to put it, in short, AngularJS’ stand out features are – Two-way data binding, MVC structure, directives, templates, dependency injections and testing.
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Six Sigma Control Plans
Suggested Courses

624 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question