Priority of a Thread (Thread Priority):
Each
thread have a priority. Priorities are represented by a number between 1 and
10. In most cases, thread schedular schedules the threads according to their
priority (known as preemptive scheduling). But it is not guaranteed because
it depends on JVM specification that which scheduling it chooses.
|
3 constants defiend in Thread class:
1. public
static int MIN_PRIORITY
2. public
static int NORM_PRIORITY
3. public
static int MAX_PRIORITY
|
Default
priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and
the value of MAX_PRIORITY is 10.
|
Example
of priority of a Thread:
1. class TestMultiPriority1 extends Thread{
2. public void run(){
3. System.out.println("running thread name is:"+Thread.currentThread().getName());
4. System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
5.
6. }
7. public static void main(String args[]){
8. TestMultiPriority1 m1=new TestMultiPriority1();
9. TestMultiPriority1 m2=new TestMultiPriority1();
10. m1.setPriority(Thread.MIN_PRIORITY);
11. m2.setPriority(Thread.MAX_PRIORITY);
12. m1.start();
13. m2.start();
14.
15. }
16. }
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
Daemon Thread in Java
Daemon thread in java is a service provider thread that provides
services to the user thread. Its life depend on the mercy of user threads i.e.
when all the user threads dies, JVM terminates this thread automatically.
There are many java daemon
threads running automatically e.g. gc, finalizer etc.
You can see all the detail by
typing the jconsole in the command prompt. The jconsole tool provides
information about the loaded classes, memory usage, running threads etc.
Points to remember for Daemon Thread in Java
- It
provides services to user threads for background supporting tasks. It has
no role in life than to serve user threads.
- Its
life depends on user threads.
- It
is a low priority thread.
Why JVM terminates
the daemon thread if there is no user thread?
The sole purpose of the daemon
thread is that it provides services to user thread for background supporting
task. If there is no user thread, why should JVM keep running this thread. That
is why JVM terminates the daemon thread if there is no user thread.
Methods
for Java Daemon thread by Thread class
The java.lang.Thread class
provides two methods for java daemon thread.
No.
|
Method
|
Description
|
1)
|
public
void setDaemon(boolean status)
|
is
used to mark the current thread as daemon thread or user thread.
|
2)
|
public
boolean isDaemon()
|
is
used to check that current is daemon.
|
Simple
example of Daemon thread in java
File:
MyThread.java
1. public class TestDaemonThread1 extends Thread{
2. public void run(){
3. if(Thread.currentThread().isDaemon()){//checking for daemon thread
4. System.out.println("daemon thread work");
5. }
6. else{
7. System.out.println("user thread work");
8. }
9. }
10. public static void main(String[] args){
11. TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
12. TestDaemonThread1 t2=new TestDaemonThread1();
13. TestDaemonThread1 t3=new TestDaemonThread1();
14.
15. t1.setDaemon(true);//now t1 is daemon thread
16.
17. t1.start();//starting threads
18. t2.start();
19. t3.start();
20. }
21. }
Output
daemon thread work
user thread work
user thread work
Note: If you want to make a user thread as Daemon, it must
not be started otherwise it will throw IllegalThreadStateException.
File:
MyThread.java
1. class TestDaemonThread2 extends Thread{
2. public void run(){
3. System.out.println("Name: "+Thread.currentThread().getName());
4. System.out.println("Daemon: "+Thread.currentThread().isDaemon());
5. }
6.
7. public static void main(String[] args){
8. TestDaemonThread2 t1=new TestDaemonThread2();
9. TestDaemonThread2 t2=new TestDaemonThread2();
10. t1.start();
11. t1.setDaemon(true);//will throw exception here
12. t2.start();
13. }
14. }
Output:exception in thread main: java.lang.IllegalThreadStateException
Java Thread Pool
Java Thread pool represents a group of worker threads that
are waiting for the job and reuse many times.
In case of thread pool, a group
of fixed size threads are created. A thread from the thread pool is pulled out
and assigned a job by the service provider. After completion of the job, thread
is contained in the thread pool again.
Advantage of Java Thread
Pool
Better performance It saves time because there is no need to
create new thread.
Real time usage
It is used in Servlet and JSP
where container creates a thread pool to process the request.
Example
of Java Thread Pool
Let's see a simple example of
java thread pool using ExecutorService and Executors.
File:
WorkerThrad.java
1. import java.util.concurrent.ExecutorService;
2. import java.util.concurrent.Executors;
3. class WorkerThread implements Runnable {
4. private String message;
5. public WorkerThread(String s){
6. this.message=s;
7. }
8. public void run() {
9. System.out.println(Thread.currentThread().getName()+" (Start) message = "+message);
10. processmessage();//call processmessage method that sleeps the thread for 2 seconds
11. System.out.println(Thread.currentThread().getName()+" (End)");//prints thread name
12. }
13. private void processmessage() {
14. try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }
15. }
16. }
File:
JavaThreadPoolExample.java
1. public class TestThreadPool {
2. public static void main(String[] args) {
3. ExecutorService executor = Executors.newFixedThreadPool(5);//creating a pool of 5 threads
4. for (int i = 0; i < 10; i++) {
5. Runnable worker = new WorkerThread("" + i);
6. executor.execute(worker);//calling execute method of ExecutorService
7. }
8. executor.shutdown();
9. while (!executor.isTerminated()) { }
10.
11. System.out.println("Finished all threads");
12. }
13. }
Output:
pool-1-thread-1 (Start) message = 0
pool-1-thread-2 (Start) message = 1
pool-1-thread-3 (Start) message = 2
pool-1-thread-5 (Start) message = 4
pool-1-thread-4 (Start) message = 3
pool-1-thread-2 (End)
pool-1-thread-2 (Start) message = 5
pool-1-thread-1 (End)
pool-1-thread-1 (Start) message = 6
pool-1-thread-3 (End)
pool-1-thread-3 (Start) message = 7
pool-1-thread-4 (End)
pool-1-thread-4 (Start) message = 8
pool-1-thread-5 (End)
pool-1-thread-5 (Start) message = 9
pool-1-thread-2 (End)
pool-1-thread-1 (End)
pool-1-thread-4 (End)
pool-1-thread-3 (End)
pool-1-thread-5 (End)
Finished all threads
No comments:
Post a Comment