我有一个java线程代码。我有 3 个线程,我给它们都起了名字。2 个消费者线程名称Consumer1
和Consumer2
. 一个名为 的生产者线程Producer
。我有一个同步方法,我尝试比较线程的名称。我希望如果线程名称是 consumer2,我希望它休眠一段时间。像这样:
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;
}
}
我一个接一个地启动所有线程,第一个生产者和消费者。如果我在所有地方都可以看到 threadName,会发生Consumer1
什么Consumer2
。但是在第二个sop中我看到了这样的东西!!!
线程名称:Consumer2 false
现在,由于方法是同步的,因此线程在进入时会对其进行锁定。因此,如果是 Consumer2,那么当两个语句都背靠背时,它与字符串“Consumer2”的比较怎么会失败?
这是线程的主要方法和调用。
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();
}
}