Friday, 13 July 2018

Java Thread


Java Thread
In this post you will learn about Thread in Java. here we explains about Java Thread . It is very
important to make your program detect and resolve the Thread situations.
This article explains you about Java Thread with an example code.
When two threads or processes are waiting for each other to release the resource or object they holds and so are
blocked forever. This situation is called deadlock. For example if one thread is holding the lock on some object that
the other thread is waiting for and the other thread is holding lock on some object the first one is waiting for then
they both will wait for each other to release the object they need to finish their operation but no one will release the
hold object and so they will wait for each other forever.

Example to show Thread condition:
In this example, there are two thread objects my Thread and your Thread. When my Thread starts running it holds
lock on str1 object. If now your Thread strarts it gets lock on str2. Now when first thread continues and wants lock on str2 then it is not available because second thread
already holds lock on str2. Now both thread will wait for each other. my Thread waits for str2 to be released by your Thread and your Thread is waiting for str1 to be released by
my Thread. This program now goes to deadlock condition. Now if you want to break the program then you need to press CTRL and C from keyboard.
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author rajesh kumar shukla
 */
public class javathred extends Thread {
public static String str1 = "str1";
public static String str2 = "str2";
public static void main(String[] a) {
Thread myThread = new MyThread();
Thread yourThread = new YourThread();
myThread.start();
yourThread.start();
}
private static class MyThread extends Thread {
public void run() {
synchronized (str1) {
System.out.println("MyThread Holds lock on object str1");
try {
Thread.sleep(10);
}
catch (InterruptedException e) {
}
System.out.println("MyThread waiting for lock on object str2");
synchronized (str2) {
System.out.println("MyThread Holds lock on objects str1, str2");
}
}
}
}
private static class YourThread extends Thread {
public void run() {
synchronized (str2) {
System.out.println("YourThread Holds lock on object str2");
try {
Thread.sleep(10);
}
catch (InterruptedException e) {}
System.out.println("YourThread waiting for lock on object str1");
synchronized (str1) {
System.out.println("YourThread Holds lock on objects str1, str2");
}
}
}
}
}

0 comments:

Post a Comment