Correctly synchronizing Vector in java threads
In a classic consumer\producer threads senario and i have to use a vector for the queue. Since I need one thread to wait to the other until there's an element in the vector, i tried the following method:
public synchronized QueueLine getCustomer(int index)
{
while (Customers.isEmpty())
{
try
{
wait();
}
catch (InterruptedException e) {}
}
return Customers.elementAt(index);
}
开发者_C百科
while the other thread adds to the "customers" vector and than use notify. i know i'm doing something worng since once the notify() doesn't effects the other thread.
You are synchronizing on the consumer instance. I think you should synchronize on the Vector
:
public QueueLine getCustomer(int index) {
synchronized (Customers) {
while (Customers.isEmpty()) {
Customers.wait();
}
return Customers.elementAt(index);
}
}
In the producer, you should do the same: synchronize and notify on the Vector
.
Well this should actually work and is one of the usual methods to implement this (ie if something doesn't work there's probably a bug in the other half of your code we don't see here). But really there's no reason to implement something like this yourself (except for homework ;)) since there's the perfectly fine java concurrent package which has several possible solutions for this problem.
The 1:1 implementation of what you want would be a BlockingQueue (well one of its implementations - pick one that best fits your model).
If you really need to use a class that has been deprecated since java 1.2 or so, you should post more of your code so we can figure out what exactly is wrong.
精彩评论