Creating threads with java.lang.Thread class

The following program (CreateThread.java) demonstrates a method for creating threads with the java.lang.Thread class. The program code is given below for analysis. At the bottom, the fields, constructors and methods of the Thread class are also described for ready reference.

CreateThread.java

class MyThread extends Thread {

MyThread(String name) {
super(name);
System.out.println(name + " started.");
start();
}

@Override
public void run() {
try {
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName() + " is running..");
Thread.sleep(500);
}
}
catch(InterruptedException e) {
System.out.println(e);
}
System.out.println(Thread.currentThread().getName() + " ended.");
}
}

public class CreateThread {

public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + " started.");

// Creating object of MyThread class
MyThread t = new MyThread("MyThread");

try {
for (int i = 0; i < 5; i++) {
System.out.println((Thread.currentThread()).getName()
+ " thread is running...");
Thread.sleep(500);
}
}
catch (InterruptedException e) {
System.out.println(e);
}

System.out.println(Thread.currentThread().getName() + " ended.");
}
}

 

Output:

First run of the program is given below.

main started.
MyThread started.
main thread is running...
MyThread is running..
main thread is running...
MyThread is running..
main thread is running...
MyThread is running..
main thread is running...
MyThread is running..
main thread is running...
MyThread is running..
main ended.
MyThread ended.

 

Second run of the program is given below.

main started.
MyThread started.
main thread is running...
MyThread is running..
MyThread is running..
main thread is running...
MyThread is running..
main thread is running...
MyThread is running..
main thread is running...
MyThread is running..
main thread is running...
MyThread ended.
main ended.

 

Explanation

It is to be noted that each run of the program produces different output sequences in terms of thread execution. In fact, as programmers, we can’t control the execution sequences of threads. Basically, the execution sequences of threads is controlled by the thread scheduler. That is why the output is completely unpredictable.

 

A closer look at the java.lang.Thread Class

Thread class signature:

public class Thread extends Object implements Runnable

Thread class is created from Object class and Runnable Interface.

Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.

When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:

  • The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
  • All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.
 
Field Description

Field Summary

static int

MAX_PRIORITY
          The maximum priority that a thread can have.

static int

MIN_PRIORITY
          The minimum priority that a thread can have.

static int

NORM_PRIORITY
          The default priority that is assigned to a thread.

 

Thread has following Range of Priority

    /**
     * The minimum priority that a thread can have.
     */
    public final static int MIN_PRIORITY = 1;

   /**
     * The default priority that is assigned to a thread.
     */
    public final static int NORM_PRIORITY = 5;

    /**
     * The maximum priority that a thread can have.
     */
    public final static int MAX_PRIORITY = 10;
 
Constructor Description

Constructor Summary

Thread()
          Allocates a new Thread object.

Thread(Runnable target)
          Allocates a new Thread object.

Thread(Runnable target, String name)
          Allocates a new Thread object.

Thread(String name)
          Allocates a new Thread object.

Thread(ThreadGroup group, Runnable target)
          Allocates a new Thread object.

Thread(ThreadGroup group, Runnable target, String name)
          Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group.

Thread(ThreadGroup group, Runnable target, String name, long stackSize)
          Allocates a new Thread object so that it has target as its run object, has the specified name as its name, belongs to the thread group referred to by group, and has the specified stack size.

Thread(ThreadGroup group, String name)
          Allocates a new Thread object.

 
Method Description

Method Summary

static int

activeCount()
          Returns the number of active threads in the current thread’s thread group.

 void

checkAccess()
          Determines if the currently running thread has permission to modify this thread.

 int

countStackFrames()
          Deprecated. The definition of this call depends on suspend(), which is deprecated. Further, the results of this call were never well-defined.

static Thread

currentThread()
          Returns a reference to the currently executing thread object.

 void

destroy()
          Destroys this thread, without any cleanup.

static void

dumpStack()
          Prints a stack trace of the current thread.

static int

enumerate(Thread[] tarray)
          Copies into the specified array every active thread in the current thread’s thread group and its subgroups.

 ClassLoader

getContextClassLoader()
          Returns the context ClassLoader for this Thread.

 String

getName()
          Returns this thread’s name.

 int

getPriority()
          Returns this thread’s priority.

 ThreadGroup

getThreadGroup()
          Returns the thread group to which this thread belongs.

static boolean

holdsLock(Object obj)
          Returns true if and only if the current thread holds the monitor lock on the specified object.

 void

interrupt()
          Interrupts this thread.

static boolean

interrupted()
          Tests whether the current thread has been interrupted.

 boolean

isAlive()
          Tests if this thread is alive.

 boolean

isDaemon()
          Tests if this thread is a daemon thread.

 boolean

isInterrupted()
          Tests whether this thread has been interrupted.

 void

join()
          Waits for this thread to die.

 void

join(long millis)
          Waits at most millis milliseconds for this thread to die.

 void

join(long millis, int nanos)
          Waits at most millis milliseconds plus nanos nanoseconds for this thread to die.

 void

resume()
          Deprecated. This method exists solely for use with suspend(), which has been deprecated because it is deadlock-prone.

 void

run()
          If this thread was constructed using a separate Runnable run object, then that Runnable object’s run method is called; otherwise, this method does nothing and returns.

 void

setContextClassLoader(ClassLoader cl)
          Sets the context ClassLoader for this Thread.

 void

setDaemon(boolean on)
          Marks this thread as either a daemon thread or a user thread.

 void

setName(String name)
          Changes the name of this thread to be equal to the argument name.

 void

setPriority(int newPriority)
          Changes the priority of this thread.

static void

sleep(long millis)
          Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.

static void

sleep(long millis, int nanos)
          Causes the currently executing thread to sleep (cease execution) for the specified number of milliseconds plus the specified number of nanoseconds.

 void

start()
          Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

 void

stop()
          Deprecated. This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked

 void

stop(Throwable obj)
          Deprecated. This method is inherently unsafe. An additional danger of this method is that it may be used to generate exceptions that the target thread is unprepared to.

 void

suspend()
          Deprecated. This method has been deprecated, as it is inherently deadlock-prone..

 String

toString()
          Returns a string representation of this thread, including the thread’s name, priority, and thread group.

static void

yield()
          Causes the currently executing thread object to temporarily pause and allow other threads to execute.

 

In the next section, the technique for creating threads with the Runnable interface is given.