Saturday, November 26, 2011

Yes this works

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.check;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
*
* @author gagandsi
*/
public class ThreadChck {

public static Object check = new Object();
public static volatile int flag= 0;
static{
System.out.println("hi");

}

public static void main(String args[]){
ThreadChck obj= new ThreadChck();
new Thread(obj.new worker1()).start();
new Thread(obj.new worker2()).start();
}

class worker1 implements Runnable {

@Override
public void run() {
while(true)
synchronized(ThreadChck.check ){
try {
ThreadChck.check.wait(200);
if(flag==1){
System.out.println("a");
flag=0;}
} catch (InterruptedException ex) {
Logger.getLogger(ThreadChck.class.getName()).log(Level.SEVERE, null, ex);
}


}

}

}
class worker2 implements Runnable {

@Override
public void run() {
while(true)
synchronized(ThreadChck.check ){
try {
ThreadChck.check.wait(200);
if(flag==0){
System.out.println("b");
flag=1;}
} catch (InterruptedException ex) {
Logger.getLogger(ThreadChck.class.getName()).log(Level.SEVERE, null, ex);
}


}

}
}
}

No comments: