Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

ADVANCED JAVA PROGRAMMING All Java programs have at least one thread of execution, called the main thread, which is given to the program automatically when

ADVANCED JAVA PROGRAMMING

All Java programs have at least one thread of execution, called the main thread, which is given to the program automatically when it begins running.

So far, we have been taking the main thread for granted.

In this project, you will show us that the main thread can be handled just like all other threads.

1- Create a file called UseMain.java

2- To access the main thread, you must obtain a Thread object that refers to it. You do this by calling thecurrentThread() method, which is a 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. Therefore, if you call curentThread() while execution is inside the mian thread, you will obtain a reference to the main thread.

Once you have this reference, you can control the main thread just like any other thread.

3- Your program should contain a reference to the main thread, and then gets and sets the main thread's name and priority.

4- The sample output from the program is shown here:

Main thread is called: main

Priority: 5

Setting name and priority.

Main thread is now called: Thread

#1Priority is now: 8

5- You need to be careful about what operations you perform on the main thread. For example if you add the following code to the end of main(), the program will never terminate because it will be waiting for the main thread to end!

try{

thrd. join();

}

catch(InterruptedException exc){

System.out.println("Interrupted");

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions