Menu
Topics Index
...
`


Multithreaded Programming >
Siva Nookala - 06 Oct 2016
Thread in Java is the path followed when executing a program. All Java programs have at least one thread, known as the main thread, which is created by the JVM at the program’s start, when the main() method is invoked with the main thread. In Java, creating a thread is accomplished by two ways one by implementing Runnable interface and the other by extending Thread class. Every Java thread is created and controlled by the java.lang.Thread class.

Note: When a thread start method is invoked it automatically invokes thread run method.

Thread Constructors
constructor Description
Thread() Allocates a new Thread object. This constructor has the same effect as Thread (null, null, gname), where gname is a newly generated name. Automatically generated names are of the form "Thread-"+n, where n is an integer.
Thread(String name) Allocates a new Thread object. name is the name of the new thread
Thread(Runnable target) Allocates a new Thread object. The parameter target is the object whose run method is invoked when this thread is started. If null, thread class run method does nothing.
Thread(Runnable target, String name) Allocates a new Thread object. The parameter group is the thread group. The parameter target is the object whose run method is invoked when this thread is started. If null, this thread's run method is invoked.
Thread Methods
Method Description
void start() This method causes the current thread to begin execution; the Java Virtual Machine calls the run method of this thread.
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
Simple Thread Program
class SimpleThread extends Thread
{
    public static void main(String[] args)
    {
        SimpleThread st = new SimpleThread(); // LINE A
        st.start(); // LINE B
    }
    
    public void run()
    {
        System.out.println("Thread running...");
    }
    

}
OUTPUT

Thread running...

DESCRIPTION

In the above program our class SimpleThread extends Thread so we can create Threads for our class as like we have done at LINE A. At LINE B we started the thread using Thread's start method which internally calls Thread's run method. Since we created a thread for SimpleThread it's run method is called.

THINGS TO TRY
  • Create one more thread for SimpleThread
    Thread t2 = new SimpleThread();
    t2.start();
Other Thread Methods :
Method Description
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.
static int enumerate(Thread[] tarray) Copies into the specified array every active thread in the current thread's thread group and its subgroups.
long getId() Returns the identifier of this Thread.
String getName() Returns this thread's name.
int getPriority() Returns thread's priority.
Thread.State getState() Returns the state of this thread.
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 current thread is a daemon thread.
boolean isInterrupted() Tests whether current thread has been interrupted.
void join() Waits for current thread to die.
void join(long millis) Waits at most millis milliseconds for this thread to die.
void setDaemon(boolean on) Marks current thread as either a daemon thread or a user thread.
void setName(String name) Changes the name of the current 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, subject to the precision and accuracy of system timers and schedulers.
String toString() Returns a string representation of current thread, including the thread's name, priority, and thread group.
static void yield() This method causes the currently executing thread object to temporarily pause and allow other threads to execute.
ThreadDemo
class ThreadDemo
{
    public static void main(String arg[])
    {
        Thread threadOne = new Thread(); // LINE A
        System.out.println("Default Name: " + threadOne.getName());
        System.out.println("Default Priority: " + threadOne.getPriority() + "\n ");
                
        threadOne.setName("threadOne"); // setting name
        threadOne.setPriority(1); //setting minimum priority
                
        System.out.println("Current Name: " + threadOne.getName());
        System.out.println("Current Priority: " + threadOne.getPriority() + "\n ");
        
        System.out.println("ThreadID: " + threadOne.getId()); //returns unique Id
        System.out.println("threadOne isAlive: " + threadOne.isAlive() +"\n ");
                
        ClassImplementsRunnable td = new ClassImplementsRunnable();
        Thread runthread = new Thread(td, "runthread"); // LINE B
        runthread.start(); // LINE C    
    }
}

class ClassImplementsRunnable implements Runnable {
    public void run() {
        System.out.println("i am running");
    }
}
OUTPUT

Default Name: Thread-0
Default Priority: 5

Current Name: threadOne
Current Priority: 1

ThreadID: 9
threadOne isAlive: false

i am running

DESCRIPTION

In the above program at LINE A we have created a Thread with reference threadOne and set its name and priority using setName() and setPriority() methods. getId() of thread class returns the unique Id of the thread, this unique Id is generated by the JVM to identify the threads. At LINE B we used Thread(Runnable target, String name) constructor to create a thread for ClassImplementsRunnable object and invoked run() method of that class by calling start() method at LINE C.

THINGS TO TRY
  • Create thread with the name ThreadFirst using constructor Thread(String name) and set is priority to 10.
  • Display the priority of the ThreadFirst using getPriority() method.
  • Create one more thread for the ClassImplementRunnable class and invoke run() method.
More details on threads are discussed in Creation Of Threads In Java

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.