Let’s See A Sample Code For IsDaemon() And SetDaemon() Method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
package com.techbeamers.multithreading;
class DaemonThreadDemo
{
public static void main (String [] args)
{
MyThread mt = new MyThread ();
mt.setDaemon (true);
mt.start ();
try
{
Thread.sleep (100);
}
catch (InterruptedException e)
{
}
}
}
class MyThread extends Thread
{
public void run ()
{
System.out.println ("Daemon is " + isDaemon ());
}
}
|
Thread CurrentThread():
It returns the instance reference of the currently executing thread.
Thread.State GetState():
It returns the state of the thread.
Let’s See A Sample Code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
package com.techbeamers.multithreading;
class ThreadStateTest
{
public static void main (String [] args)
{
Thread currentThread = Thread.currentThread();
System.out.println(currentThread);
MyThread mt1 = new MyThread ();
mt1.setName("MyThread1");
MyThread mt2 = new MyThread();
mt1.setName("MyThread2");
System.out.println("Thread State of MyThread1 before calling start: "+mt1.getState());
mt1.start ();
mt2.start();
System.out.println("Thread State of MyThread1 in Main method before Sleep: " + mt1.getState());
System.out.println("Thread State of MyThread2 in Main method before Sleep: " + mt2.getState());
try
{
Thread.sleep (1000);
}
catch (InterruptedException e)
{
}
System.out.println("Thread State of MyThread1 in Main method after Sleep: " + mt1.getState());
System.out.println("Thread State of MyThread2 in Main method after Sleep: " + mt2.getState());
}
}
class MyThread extends Thread
{
public void run ()
{
System.out.println ("Run by " + Thread.currentThread().getName());
try
{
Thread.sleep (100);
}
catch (InterruptedException e)
{
}
System.out.println("Thread State of: "+ Thread.currentThread().getName()+ " - "+Thread.currentThread().getState());
System.out.println("Exit of Thread: " + Thread.currentThread().getName());
}
}
|
Sample Output.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
Output:
Thread[main,5,main]
Thread State of MyThread1 before calling start: NEW
Run by MyThread2
Thread State of MyThread1 in Main method before Sleep: RUNNABLE
Run by Thread-1
Thread State of MyThread2 in Main method before Sleep: RUNNABLE
Thread State of: MyThread2 - RUNNABLE
Exit of Thread: MyThread2
Thread State of: Thread-1 - RUNNABLE
Exit of Thread: Thread-1
Thread State of MyThread1 in Main method after Sleep: TERMINATED
Thread State of MyThread2 in Main method after Sleep: TERMINATED
|
Yield():
This method causes the currently executing thread object to pause temporarily and allow other threads to run.
Let’s see a sample code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
package com.techbeamers.multithreading;
public class ThreadTest extends Thread
{
public void run()
{
System.out.println("In run");
yield();
System.out.println("Leaving run");
}
public static void main(String []argv)
{
(new ThreadTest()).start();
}
}
|
The thread will halt after printing “In Run” due to the yield() method; since there is no other thread to execute so this thread will resume and print “Leaving run”.
|
Output:
In Run
Leaving Run
|
Final Int GetPriority():
It returns the priority of the thread.
Final Void SetPriority(Int Priority):
This function is used to change the priority of a thread.
Let’s see a sample code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
package com.techbeamers.multithreading;
public class ThreadDemo {
public static void main(String[] args) {
Thread t = Thread.currentThread();
t.setName("Admin Thread");
// set thread priority to 1
t.setPriority(1);
// prints the current thread
System.out.println("Thread = " + t);
int priority= t.getPriority();
System.out.println("Thread priority= " + priority);
int count = Thread.activeCount();
System.out.println("currently active threads = " + count);
}
}
|
|
Output:
Thread = Thread[Admin Thread,1,main]
Thread priority= 1
currently active threads = 1
|
Int GetId():
It returns the id of the thread.
Interrupt():
It interrupts the thread.
Boolean IsInterrupted():
tests if the thread has been interrupted and returns the interrupted flag either true or false.
Boolean Interrupted():
The static interrupted() method tests if the thread has been interrupted.This method returns the interrupted flag after that it sets the flag to false if it is true.
Let’s see a sample code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
package com.techbeamers.multithreading;
public class TestThreadInterrupt extends Thread {
public void run() {
for (int i = 1; i <= 2; i++) {
if (Thread.interrupted()) {
System.out.println("code for interrupted thread");
} else {
System.out.println("code for normal thread");
}
} //end of for loop
}
public static void main(String args[]) {
TestThreadInterrupt t1 = new TestThreadInterrupt();
TestThreadInterrupt t2 = new TestThreadInterrupt();
t1.start();
t1.interrupt();
t2.start();
}
}
|
|
Output:
code for interrupted thread
code for normal thread
code for normal thread
code for normal thread
|
Suspend():
You can use it to suspend the thread. [deprecated]
Resume():
You can use it to resume the suspended thread. [deprecated]
Stop():
You can use it to halt the thread. [deprecated]
Note: Sun has deprecated a variety of Thread methods, such as suspend(), resume() and stop() because they can lock up your programs or damage objects. As a result, you should not call them in your code.
We’ve covered almost all the important areas of Java Thread class in the above section, hope it would help. In the next segment, you’ll see the two methods to create threads in Java.
Java Thread Creation Methods And Examples.
Create Thread By Extending The Thread Class.
In this case, you need to complete the following steps to spawn a thread in a Java program.
- Add a new class that extends the Thread class.
- This newly created class should override the Run() method which is the entry point for the new thread.
- Invokes the start() method to initiate the execution of the thread.
Let’s see a sample code as an example.
1
2
3
4
5
6
7
8
9
10
11
12
|
package com.techbeamers.multithreading;
class MultithreadDemo extends Thread{
public void run(){
System.out.println("My thread is in running state.");
}
public static void main(String args[]){
MultithreadDemo obj=new MultithreadDemo();
obj.start();
}
}
|
|
Output:
My thread is in running state
|
Create Thread By Implementing The Runnable Interface.
For this approach, you need to follow the below steps to create a thread.
- Create a class that does the following.
- Implements the Runnable interface.
- Provides the implementation of the run() method.
- The run() method is an entry point for the thread and it remains alive till the run() method finishes its execution.
- Once you create the thread, bring it to the Running state by calling the start() method.
- Note: The start() method calls the run() method implicitly.
Let’s see a sample code as an example.
1
2
3
4
5
6
7
8
9
10
11
12
13
|
package com.techbeamers.multithreading;
class MultithreadDemo implements Runnable{
public void run(){
System.out.println("My thread is in running state.");
}
public static void main(String args[]){
MultithreadDemo obj=new MultithreadDemo();
Thread threadobj = new Thread(obj);
threadobj.start();
}
}
|
|
Output:
My thread is in running state
|
Download Java Multithreading Code Samples.
Now it’s time to download the sample projects so that you can easily understand the Java multithreading code snippets specified in this post. Please use the below link to start your download.
If you don’t have Java SDK it on your system, please
click here to download it. In case, you don’t already have Eclipse IDE then refer
the link to get it now.
Summary – Java Multithreading.
We wish that the above Java multithreading tutorial would have helped you in walking a step further on the Java learning scale. In the next article of Java programming, we’ll give insights on different ways to implement synchronization in Java applications.
In case, this post was able to intrigue you then please share it with your friends or float on social media using the below share icons.
No comments:
Post a Comment