Monday, 31 October 2016

How to run a shell script from Java program

This post talks about how you can execute a shell script from a Java program.

If you have a shell script say test.sh then you can run it from a Java program using RunTime class or ProcessBuilder (Note ProcessBuilder is added in Java 5).

Shell script

echo 'starting script'
mkdir test
cd test
touch SAMPLE

Using Runtime.getRunTime().exec

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class RunningSS {
 public static void main(String[] args) {
  Process p;
  try {
   String[] cmd = { "sh", "/home/adb/Documents/test.sh"};
   p = Runtime.getRuntime().exec(cmd); 
   p.waitFor(); 
   BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream())); 
   String line; 
   while((line = reader.readLine()) != null) { 
    System.out.println(line);
   } 
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

After executing this Java program with the given shell script, if you verify at the location where your Java program is you will see a directory test created and a file SAMPLE with in that directory.

Runtime.getRuntime().exec method is used to run the command.

  • public static Runtime getRuntime() - Returns the runtime object associated with the current Java application.
  • public Process exec(String command) throws IOException - Executes the specified string command in a separate process.

cmd /c which is used with the command has the following explanantion -

  • cmd - Starts a new command shell
  • /c - Executes the given command and terminates

Execution of the command returns instance of class Process. Using the getInputStream() method of Process class output of the executed command can be printed by reading the stream.

Using ProcessBuilder

If you have to run the same command using ProcessBuilder, which is a much clearer way to do that, you can create a list with the command and the required arguments and then pass it to ProcessBuilder instance as command.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class RunningSS {

    public static void main(String[] args) {
        Process p;
        try {
            
            List<String> cmdList = new ArrayList<String>();
            // adding command and args to the list
            cmdList.add("sh");
            cmdList.add("/home/adb/Documents/test.sh");
            ProcessBuilder pb = new ProcessBuilder(cmdList);
            p = pb.start();
                
            p.waitFor(); 
            BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream())); 
            String line; 
            while((line = reader.readLine()) != null) { 
                System.out.println(line);
            } 
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

That's all for this topic How to run a shell script from Java program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to compile Java program at runtime
  2. How to run javap programmatically from Java Program
  3. Running Dos/Windows commands from Java program
  4. Zipping files in Java
  5. How to create deadlock in Java multi-threading - Java Program

You may also like -

>>>Go to Java Programs page

Friday, 28 October 2016

Running Dos/Windows commands from Java program

If you want to run DOS/Windows commands from a Java program it can be done using RunTime class or ProcessBuilder (Note ProcessBuilder is added in Java 5).

Using Runtime.getRunTime().exec

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class RunningCommand {

    public static void main(String[] args) {
        Process p;
        try {
            p = Runtime.getRuntime().exec("cmd /c dir");
    
            p.waitFor(); 
            BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream())); 
            String line; 
            while((line = reader.readLine()) != null) { 
                System.out.println(line);
            } 
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Output

Volume in drive C is OS
Volume Serial Number is AEC2-FEE9

 Directory of C:\workspace\abc

10/19/2016  12:39 PM    <DIR>          .
10/19/2016  12:39 PM    <DIR>          ..
10/24/2016  03:22 PM               592 .classpath
10/19/2016  12:39 PM               379 .project
10/19/2016  12:39 PM    <DIR>          .settings
10/21/2016  03:16 PM    <DIR>          bin
10/19/2016  12:39 PM    <DIR>          src
               2 File(s)            971 bytes
               5 Dir(s)  40,032,706,560 bytes free

Here it can be seen that directory listing is displayed for the directory which happens to be the workspace directory from where I executed the Java program.

Runtime.getRuntime().exec method is used to run the command.

  • public static Runtime getRuntime() - Returns the runtime object associated with the current Java application.
  • public Process exec(String command) throws IOException - Executes the specified string command in a separate process.

cmd /c which is used with the command has the following explanantion -

  • cmd - Starts a new command shell
  • /c - Executes the given command and terminates

Execution of the command returns instance of class Process. Using the getInputStream() method of Process class output of the executed command can be printed by reading the stream.

Running command Using ProcessBuilder

If you have to run the same command using ProcessBuilder, which is a much clearer way to do that, you can create a list with the command and the required arguments and then pass it to ProcessBuilder instance as command.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class RunningCommand {

    public static void main(String[] args) {
        Process p;
        try {
            List<String> cmdList = new ArrayList<String>();
            cmdList.add("cmd");
            cmdList.add("/c");
            cmdList.add("dir");
            ProcessBuilder pb = new ProcessBuilder();
            pb.command(cmdList);
            p = pb.start();
    
            p.waitFor(); 
            BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream())); 
            String line; 
            while((line = reader.readLine()) != null) { 
                System.out.println(line);
            } 
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

That's all for this topic Running Dos/Windows commands from Java program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to compile Java program at runtime
  2. How to run javap programmatically from Java Program
  3. How to run threads in sequence - Java Program
  4. How to run a shell script from Java program
  5. Print odd-even numbers using threads and wait-notify

You may also like -

>>>Go to Java Programs page

Wednesday, 26 October 2016

How to run javap programmatically from Java Program

If you have a .class file or a jar with .class files and you want to see the structure of a .class file javap is a good option to do that.

The javap command disassembles one or more class files. It comes with JDK under tools.jar and used to get the mnemonical representation of the .class file.

This post is about running javap command programmatically. It can be done using ProcessBuilder class which is used to create operating system processes.

ProcessBuilder has a constructor that takes the command as a list

  • ProcessBuilder(List<String> command) - Constructs a process builder with the specified operating system program and arguments.

You can use this constructor to construct a process with javap command, -c argument and path of the class file. Also make sure that you have tools.jar (which comes with JDK) in your classpath.

Java Program

Suppose you have a class called First.java

public class First {

 public static void main(String[] args) {
  First first = new First();
  first.showDetails();
 }
 
 public void showDetails(){
  System.out.println("In Show details" );
 }
}

You want to run javap command for the compiled .class file of First.java.

So, the command you want to run is :
javap –c First.class. Let’s see how you can run this command from a Java program.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class ClassStructure {

 public static void main(String[] args) {
  try {
   List<String> cmdList = new ArrayList<String>();
   cmdList.add("C:\\Program Files\\Java\\jdk1.8.0_111\\bin\\javap.exe");
   cmdList.add("-c");
   cmdList.add("D:\\First.class");
   
   // Constructing ProcessBuilder with List as argument
   ProcessBuilder pb = new ProcessBuilder(cmdList);
   
   Process p = pb.start();
   p.waitFor();
   InputStream fis = p.getInputStream();
   
   DisplayClassStructure(fis);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
 }
 
 // Method used for displaying the disassembled class
 private static void DisplayClassStructure(InputStream is){
  
  InputStream stream;
  
  try {
   
   BufferedReader reader = new BufferedReader(new InputStreamReader(is));
   String line;   
   while ((line = reader.readLine()) != null) {   
        System.out.println(line);   
   }
   // Better put it in finally
   reader.close();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Output

Compiled from "First.java"
public class org.test.First {
  public org.test.First();
    Code:
       0: aload_0
       1: invokespecial #8                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: new           #1                  // class org/test/First
       3: dup
       4: invokespecial #16                 // Method "<init>":()V
       7: astore_1
       8: aload_1
       9: invokevirtual #17                 // Method showDetails:()V
      12: return

  public void showDetails();
    Code:
       0: getstatic     #23                 // Field java/lang/System.out:Ljava/io/PrintStream;
       3: ldc           #29                 // String In Show details
       5: invokevirtual #31                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
       8: return
}

That's all for this topic How to run javap programmatically from Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to compile Java program at runtime
  2. Unzipping files in Java
  3. Print odd-even numbers using threads and wait-notify
  4. How to find last modified date of a file in Java
  5. How to create PDF from XML using Apache FOP

You may also like -

>>>Go to Java Programs page

Monday, 24 October 2016

How to compile Java program at runtime

This post talks about how you can compile a java program at runtime. You may have a case where you get a Java file from some property file and you need to run it or Program file is created rather than some script at run time which you need to compile and run.

In such cases you need to compile your code at run time. It can be done using JavaCompiler interface and ToolProvider class. Note that these classes are provided from Java 6.

Also note that you will need JDK to run it not JRE, so you need to have JDK libraries not JRE. If you are using eclipse and your JRE System library is pointing to JRE path make sure it points to JDK. You can do that by right clicking on your project and going to Java Build Path through properties. There click on Libraries tab and select the JRE System Library which points to jre path and click Edit.

In the next dialog box you can select the path to JDK after selecting Alternate JRE.

Java code to compile Java code at runtime

Suppose there is a Java file HelloWorld.java which you need to compile at run time and execute its method displayMessage.

HelloWorld.java

public class HelloWorld {

 public static void main(String[] args) {
 

 }
 
 public void displayMessage(){
  System.out.println("Hello world from displayMessage method");
 }

}

RTComp.java

This is the class where runtime compilation is done.

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

public class RTComp {

 public static void main(String[] args) {
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  // Compiling the code
  int result = compiler.run(null, null, null, "C:\\workspace\\Test\\src\\org\\test\\HelloWorld.java");
  System.out.println("result " + result);
  // Giving the path of the class directory where class file is generated..
  File classesDir = new File("C:\\workspace\\Test\\bin\\org\\test");
  // Load and instantiate compiled class.
  URLClassLoader classLoader;
  try {
   // Loading the class 
   classLoader = URLClassLoader.newInstance(new URL[] { classesDir.toURI().toURL() });
   Class<?> cls;
   
   cls = Class.forName("org.test.HelloWorld", true, classLoader);
  
   HelloWorld instance = (HelloWorld)cls.newInstance();
   instance.displayMessage();
  } catch (MalformedURLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } // Should print "hello".
  catch (InstantiationException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }  
 }
}

Output

result 0
Hello world from displayMessage method

Here it can be seen that compiler.run method is provided with the path of the class HelloWorld. Here I have used the package as org.test.

Also in eclipse, by default, bin is the location for putting .class files so that path is provided for the generated class. Once the java file is compiled it is loaded using the class loader and an instance of that class is created. Using that instance method of that class is called at runtime.

That's all for this topic How to compile Java program at runtime. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to run javap programmatically from Java Program
  2. How to find last modified date of a file in Java
  3. How to iterate a Hash map of arraylists of String in Java?
  4. Lambda Expression Comparator example
  5. Print odd-even numbers using threads and wait-notify

You may also like -

>>>Go to Java Programs page

Thursday, 20 October 2016

How to create deadlock in Java multi-threading - Java Program

This post is about creating a deadlock in a multi-threaded Java Program.

Deadlock can happen if there are nested synchronized blocks in your code. There are 2 things to note here -

  • Locks are acquired at object level.
  • Thread which has acquired that lock only can enter the synchronized block.

Logic for the Java program is that there are two Thread classes ThreadA and ThreadB and there are two objects of the class DeadLckDemo. In both of these classes ThreadA and ThreadB there are nested synchronized blocks and the object reference provided in the blocks is reversed in both of those classes.

In one of the classes if nested blocks are as -

synchronized(obj1){
    System.out.println("" + Thread.currentThread().getName());
    synchronized(obj2){
     System.out.println("Reached here");
    }
}

Then in other class it is like this -

synchronized(obj2){
    System.out.println("" + Thread.currentThread().getName());
    synchronized(obj1){
        System.out.println("Reached here");
    }
}

If two threads are started, one for ThreadA and another one for ThreadB. Thread t1 will acquire a lock on obj1 and enter the outer synchronized block. Meanwhile thread t2 will start and get a lock on obj2 and enter the outer block in ThreadB class. That's where both of these threads will enter in a deadlock.

Thread t1 will try to acquire lock on object obj2 which is currently held by thread t2 whereas thread t2 will try to acquire a lock on object obj1 which is curretly held by thread t1. That way these threads will wait for each other to release locks on respective objects and create a deadlock.

Java Program to create deadlock

public class DeadLckDemo {
    public static void main(String[] args) {
     DeadLckDemo obj1 = new DeadLckDemo();
     DeadLckDemo obj2 = new DeadLckDemo();
        Thread t1 = new Thread(new ThreadA(obj1, obj2), "Thread-1");
        Thread t2 = new Thread(new ThreadB(obj1, obj2), "Thread-2");
        
        t1.start();
        
        t2.start();
    }
}

class ThreadA implements Runnable{
    private DeadLckDemo obj1;
    private DeadLckDemo obj2;
    ThreadA(DeadLckDemo obj1, DeadLckDemo obj2){
        this.obj1 = obj1;
        this.obj2 = obj2;
    }
    @Override
    public void run() {
        synchronized(obj1){
            System.out.println("" + Thread.currentThread().getName());
            synchronized(obj2){
                System.out.println("Reached here");
            }
        }
        
    }
    
}

class ThreadB implements Runnable{

    private DeadLckDemo obj1;
    private DeadLckDemo obj2;
    ThreadB(DeadLckDemo obj1, DeadLckDemo obj2){
        this.obj1 = obj1;
        this.obj2 = obj2;
    }
    @Override
    public void run() {
        synchronized(obj2){
            System.out.println("" + Thread.currentThread().getName());
            synchronized(obj1){
                System.out.println("Reached here");
            }
        }   
    }
}

That's all for this topic How to create a deadlock in Java - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Producer-Consumer Java program using wait notify
  2. Print odd-even numbers using threads and wait-notify
  3. How to run threads in sequence - Java Program
  4. Race condition in Java multi-threading
  5. Lock Striping in Java Concurrency

You may also like -

>>>Go to Java Programs page

Monday, 17 October 2016

Injecting inner bean in Spring

Let’s say you have a Java class which refers to another class object and the access type for that object is private. In that case what do you think is the best way to provide bean definition in Spring. Let me provide class (Employee) here so you can understand what I am saying.

public class Employee {
 private Person person;

 public Person getPerson() {
  return person;
 }

 public void setPerson(Person person) {
  this.person = person;
 }
 
 public String toString(){
  return "Name - " + person.getName() + "Age - " + person.getAge();
  
 }
}

Here person object is private meaning person is not shared.

Coming to Spring definition, you may use the usual way of defining Employee and Person bean separately and use “ref” attribute to reference Person bean into Employee bean. But, in that case person bean can also be reference by other beans and that same instance will be shared by all those beans. If you don’t want that to happen better use Person bean as an inner bean of Employee bean.

Note that inner beans are beans that are defined within the scope of another bean. Defining Person bean as an inner bean of Employee bean will mean that definition of Person bean is restricted with in the scope of Employee bean.

Person Class

public class Person {
 private String name;
 private int age;
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

XML Configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
  
  <bean id="employeeBean" class="org.netjs.exp.Spring_Example.Employee">
      <property name="person">
           <bean class="org.netjs.exp.Spring_Example.Person">
               <property name="name" value="Ram" />
               <property name="age" value="22" />
           </bean>
      </property>
  
  </bean>
  
</beans>

Java class to run application

public class App {
    public static void main( String[] args ){
     //AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
     ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
     Employee employee = (Employee) context.getBean("employeeBean");
     System.out.println("Employee " + employee);
        context.close();
    }
}

Output

Employee Name - RamAge - 22

Here some points to note are -

  1. An inner bean definition does not require a defined id or name; even if you provide container ignores these values.
  2. Inner bean doesn’t have its own scope. If provided container ignores the scope flag.
  3. Inner beans are always anonymous and they are always created with in the scope of outer bean.
  4. It is not possible to inject inner beans into collaborating beans other than into the enclosing bean.

Using with constructor-arg

In place of bean, constructor-arg property can also be used.

Employee class

Employee class in that case.
public class Employee {
 private Person person;
 // Constructor
 public Employee(Person person) {
  this.person = person;
 }

 public Person getPerson() {
  return person;
 }

 public void setPerson(Person person) {
  this.person = person;
 }
 
 public String toString(){
  return "Name - " + person.getName() + "Age - " + person.getAge(); 
 }
}

XML configuration with constructor-arg property

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
  
  
  <bean id="employeeBean" class="org.netjs.exp.Spring_Example.Employee">
      <constructor-arg name="person">
           <bean class="org.netjs.exp.Spring_Example.Person">
               <property name="name" value="Ram" />
               <property name="age" value="22" />
           </bean>
      </constructor-arg>
  
  </bean>
  
</beans>

That's all for this topic Injecting inner bean in Spring. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to inject prototype scoped bean in singleton bean
  2. Different bean scopes in Spring
  3. What is Dependency Injection in Spring
  4. Dependency Injection using factory-method in Spring
  5. Wiring collections in Spring

You may also like -

>>>Go to Spring tutorial page

Friday, 14 October 2016

Finding duplicate elements in an array - Java Program

If you have to find duplicate elements in an array first thing you will think is to loop through the array taking one element at a time and then compare it with all the other elements of the array in order to find the duplicates. Though this solution works fine but the problem here is you are looping though the array twice making the time complexity of this solution O(n2). Because of the double iteration program will be slow.

Thus to minimize the execution time you can think of using a data structure like HashSet which will reduce the time complexity to O(n). Since Set doesn't allow duplicate elements trying to do that will return false. So you can have a logic when ever adding an element to a HashSet returns false that means a duplicate element. As I said since array is iterated only once so time complexity is O(n) here but a new data structure is created, apart from array you are also creating a Set, so space complexity increases here. Space complexity is O(n2) for this solution.

Looping through Array and comparing elements

Here you have an outer loop that iterates the array one element at a time and another loop that starts from the next element and iterates through all the elements of the element and compares.

public class DuplicateArrayElement {

    public static void main(String[] args) {
        int[] numArray = {2, 6, 7, 6, 2, 19, 1, 19};
        for(int i = 0; i < numArray.length; i++){
            for(int j = i + 1; j < numArray.length; j++){
                if(numArray[i] == numArray[j]){
                    System.out.println("Duplicate element found " + numArray[j]);
                }
            }
        }    
    }
}

Output

Duplicate element found 2
Duplicate element found 6
Duplicate element found 19

Using HashSet

Here iteration of the array is done and elements of the array are added to the set.

Here thing to understand is - If set already contains the element, call to add method of the set leaves the set unchanged and returns false.
So, whenever false is returned that means a duplicate element.

public class DuplicateArrayElement {

    public static void main(String[] args) {
        int[] numArray = {2, 6, 7, 6, 2, 19, 1, 19};
        Set<Integer> numSet = new HashSet<Integer>();
        for(int num : numArray){
            // If add returns false
            if(!numSet.add(num)){
                System.out.println("Duplicate element found " + num);
            }
        }
    }
}

Output

Duplicate element found 2
Duplicate element found 6
Duplicate element found 19

That's all for this topic Finding duplicate elements in an array - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to iterate a Hash map of arraylists of String in Java?
  2. How to Sort elements in different order in TreeSet
  3. How to convert Array to ArrayList in Java
  4. Difference between Array and ArrayList in Java

You may also like -

>>>Go to Java Programs page

Wednesday, 12 October 2016

How to run threads in sequence - Java Program

How to make sure that threads run in sequence is a very popular multi-threading interview question. Though it doesn’t make much sense practically to do that as you use threads so that processing can be done by many threads simultaneously. But you have to answer a question if asked in interview so this post tries to gives that answer.

So, if you are asked to answer the question “How can you make sure that Thread t1, t2 and t3 are executed in such a way that t2 starts after t1 finishes and t3 starts after executing t2” you have to say using join() method it can be done.

join() method

join() method is used when you want to wait for the thread to finish. Its general form is –

public final void join() throws InterruptedException
This method waits until the thread on which it is called terminates.

As you see from the description of the join() method if it is called on any thread it will wait until the thread on which it is called terminates. Armed with this info let’s see the code now.

Example code

public class ThreadSequence {

 public static void main(String[] args) {
  SeqRun sr = new SeqRun();
  // Three threads
  Thread t1 = new Thread(sr);
  Thread t2 = new Thread(sr);
  Thread t3 = new Thread(sr);
  
  try {
   // First thread
   t1.start();
   t1.join();
   // Second thread
   t2.start();
   t2.join();
   // Third thread
   t3.start();
   t3.join();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

}

class SeqRun implements Runnable{

 @Override
 public void run() {
  System.out.println("In run method " + Thread.currentThread().getName());
  
 } 
}

Output

In run method Thread-0
In run method Thread-1
In run method Thread-2

It can be seen that threads are executed in sequence here. Thing to do here is you start the thread and call the join() method on the same thread. This makes it to wait until the thread stops executing. That way order is ensured.

For testing you can also called sleep() method on the thread inside run(), you can observe that other thread doesn’t start their execution even if the current thread is sleeping.

@Override
public void run() {
 try {
  Thread.sleep(1000);
 } catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
 System.out.println("In run method " + Thread.currentThread().getName()); 
} 

That's all for this topic How to run threads in sequence - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Print odd-even numbers using threads and wait-notify
  2. Producer-Consumer Java program using ArrayBlockingQueue
  3. String and thread-safety in Java
  4. Race condition in Java multi-threading
  5. Synchronization in Java multithreading

You may also like -

>>>Go to Java Programs page