I have a java threading code. I have 3 threads, I have given names to all of them. 2 consumer threads name Consumer1
and Consumer2
. A producer thread named Producer
. I have a synchronized method where I try to compare the names of thread. I want that if thread name is consumer2, I want it to sleep for some time. Like so:
public synchronized String getReferer()
{
try{
String threadName = Thread.currentThread().getName();
System.out.println("Thread name: "+threadName);
System.out.println(" compatre"+threadName=="Consumer2");
if(threadName == "Consumer2"){
System.out.println("It is consumer2. ...wait, you #$%^!!!");
//this.wait();
}
}catch(Exception e){
this.displayAndExit(e);
}
String line = "";
int i = 0;
try{
finished = 0;
if(this.hostnames2.isEmpty()){
line = null;
}else{
line = this.hostnames2.take();
}
}catch(Exception e){
this.displayAndExit(e);
}
return line;
}
}
I start all thread one after another, first producer and the consumers. What happens is if I s.o.p threadName I can see Consumer1
and Consumer2
all over the place. But in second s.o.p I see something like this !!!
Thread name: Consumer2 false
Now since method is synchronized, a thread will hold lock onto it when it enters. So if it is Consumer2 then how come it's comparison with string "Consumer2" fail when both statements are just back to back??
This is the main method and invocation of threads.
public class OffensiveFilterApplicator
{
public static void main(String [] args)
{
String pathToCSV = "src/unique_referer_dump3.txt";
CSVResourceHandler csvResHandler = new CSVResourceHandler(pathToCSV);
HostnameFileData hfd = new HostnameFileData();
HostnameReader hr = new HostnameReader(hfd, csvResHandler.getCSVFileHandler());
VexigoCallOps vco = new VexigoCallOps(hfd);
Thread producer = new Thread(hr);
Thread consumer1 = new Thread(vco);
Thread consumer2 = new Thread(vco);
producer.setName("Producer");
producer.start();
consumer1.setName("Consumer1");
consumer2.setName("Consumer2");
consumer1.start();
consumer2.start();
}
}