The Main Thread in Java

By: Charles Viewed: 159260 times  Printer Friendly Format    


When a Java program starts up, one thread begins running immediately. This is usually called the main thread of your program, because it is the one that is executed when your program begins. The main thread is important for two reasons:

• It is the thread from which other "child" threads will be spawned.
• It must be the last thread to finish execution. When the main thread stops, your program terminates.

Although the main thread is created automatically when your program is started, it can be controlled through a Thread object. To do so, you must obtain a reference to it by calling the method currentThread( ), which is a public static member of Thread. Its general form is shown here:

static Thread currentThread( )

This method returns a reference to the thread in which it is called. Once you have a reference to the main thread, you can control it just like any other thread.

Let's begin by reviewing the following example:

// Controlling the main Thread.
class CurrentThreadDemo {
public static void main(String args[]) {
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
// change the name of the thread
t.setName("My Thread");
System.out.println("After name change: " + t);
try {
for(int n = 5; n > 0; n—) {
System.out.println(n);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
}
}

In this program, a reference to the current thread (the main thread, in this case) is obtained by calling currentThread( ), and this reference is stored in the local variable t. Next, the program displays information about the thread. The program then calls setName( ) to change the internal name of the thread. Information about the thread is then redisplayed. Next, a loop counts down from five, pausing one second between each line. The pause is accomplished by the sleep( ) method. The argument to sleep( ) specifies the delay period in milliseconds. Notice the try/catch block around this loop. The sleep( ) method in Thread might throw an InterruptedException. This would happen if some other thread wanted to interrupt this sleeping one. This example just prints a message if it gets interrupted. In a real program, you would need to handle this differently. Here is the output generated by this program:

Current thread: Thread[main,5,main]
After name change: Thread[My Thread,5,main]

5
4
3
2
1

Notice the output produced when t is used as an argument to println( ). This displays, in order: the name of the thread, its priority, and the name of its group. By default, the name of the main thread is main. Its priority is 5, which is the default value, and main is also the name of the group of threads to which this thread belongs. A thread group is a data structure that controls the state of a collection of threads as a whole. This process is managed by the particular run-time environment and is not discussed in detail here. After the name of the thread is changed, t is again output. This time, the new name of the thread is displayed.

Let's look more closely at the methods defined by Thread that are used in the program. The sleep( ) method causes the thread from which it is called to suspend execution for the specified period of milliseconds. Its general form is shown here:

static void sleep(long milliseconds) throws InterruptedException

The number of milliseconds to suspend is specified in milliseconds. This method may throw an InterruptedException. The sleep( ) method has a second form, shown next, which allows you to specify the period in terms of milliseconds and nanoseconds:

static void sleep(long milliseconds, int nanoseconds) throws InterruptedException

This second form is useful only in environments that allow timing periods as short as nanoseconds.
As the preceding program shows, you can set the name of a thread by using setName( ). You can obtain the name of a thread by calling getName( ) (but note that this procedure is not shown in the program). These methods are members of the Thread class and are declared like this:

final void setName(String threadName)
final String getName( )

Here, threadName specifies the name of the thread.



Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial

Subscribe to Tutorials

Related Tutorials

Archived Comments

1. It must be the last thread to finish execution. Wh
View Tutorial          By: Abinash at 2013-07-16 06:37:11

2. ottima guida
mi hai risolto un grande probl

View Tutorial          By: Cioco at 2014-04-04 13:50:09

3. No Abinash.. Once the execution of main thread is
View Tutorial          By: Srikhar at 2016-06-20 14:57:27

4. Jolynspag
View Tutorial          By: Jolynspag at 2017-01-20 16:10:24

5. Jolynspag
View Tutorial          By: Jolynspag at 2017-01-23 12:53:19

6. Jewellmip
View Tutorial          By: Jolynspag at 2017-01-26 05:49:42

7. Guestchoob
View Tutorial          By: Guestchoob at 2017-02-26 05:16:46

8. JasonNix
View Tutorial          By: JasonNix at 2017-04-24 23:44:02

9. TRUE YOU NEED TO MANAGE MAIN THREAD USING YIELD ME
View Tutorial          By: Oshin Talreja at 2017-05-24 16:43:00

10. usibisuheyi
View Tutorial          By: usibisuheyi at 2017-06-08 11:45:20

11. udixudu
View Tutorial          By: udixudu at 2017-06-08 12:04:45

12. ixziwitecizob
View Tutorial          By: ixziwitecizob at 2017-06-08 12:37:07

13. ejoqunoitwce
View Tutorial          By: ejoqunoitwce at 2017-06-08 12:53:45

14. uretopuje
View Tutorial          By: uretopuje at 2017-06-10 10:01:01

15. Por que jamais #1? Uma coisa de condenvel existem
View Tutorial          By: http://evitarejaculacaoprecoce.med.br/acabar-com-a-ejaculacao-precoce at 2017-06-22 04:34:48

16. I see you don't monetize your website, don't waste
View Tutorial          By: 86Aleisha at 2017-08-09 04:01:19