javascript
Brief description  about Online courses   join in Online courses
View Santosh Kumar Mohanty 's Profile

SYNC/BLOCKS

Sir,
I Am Unable To Understand Synchronisation By Blocks So Please Help Me In UnderStanding
I Cant Find The Syntax And Logical Errors In THe Programme Below-:
public sychblock implements Runnable
{
static String msg[]={"I","LOVE","MY","MOTHERLAND"};
public sychblock()
{
Thread T;
T=new Thread (this,"SYNCHRONISATION");
}
public static void main(String s[])
{
sychblock t1=new sychblock("Thread 1");
sychblock t2= new sychblock("Thread 2");
t1.start();
t2.start();
boolean A1IsAlive = true;
boolean A2IsAlive = true;
do
{
if (A1IsAlive
Asked by Santosh Kumar Mohanty | Dec 20, 2010 |  Reply now
Replies (1)
View arun kumar das 's Profile
HI

Go through this code try to understand how Synchronization block is running.

class RunnableThread implements Runnable {

Thread RunningThread;
public RunnableThread() {
}
public RunnableThread(String ThreadName) {
RunningThread = new Thread(this, ThreadName); // (1) Create a new thread.
System.out.println(RunningThread.getName());
RunningThread.start(); // (2) Start the thread.
}
public void run() { //synchronized thread block
synchronized (this){
System.out.println (Thread.currentThread());
} }
}

public class RunnableExample {
public static void main(String[] args) {
Thread thread1 = new Thread(new RunnableThread(), "thread1");
Thread thread2 = new Thread(new RunnableThread(), "thread2");
RunnableThread thread3 = new RunnableThread("thread3");

thread1.start();
thread2.start();
boolean t1IsAlive = true;
boolean t2IsAlive = true;
do
{ //checking weather the thread is alive
if (t1IsAlive && !thread1.isAlive())
{
t1IsAlive = false;
System.out.println("thread1 is dead.");
}
if (t2IsAlive && !thread2.isAlive())
{
t2IsAlive = false;
System.out.println("thread2 is dead.");
}
} while (t1IsAlive || t2IsAlive);

try {
Thread.currentThread().sleep(1000); //sleeping the current thread for 1000ms.
}
catch (InterruptedException e) {
System.out.println("There has been an Exception, Take care of it!");
}
System.out.println(Thread.currentThread());
}
}


Java Teacher
Dec 23, 2010