is it safe for the thread from start_thread, to access packetList while the start_activity thread(main thread) is sleeping on a semaphore. If not then how can I share the resource between them, please note the access will only be read and the packetList wont be changed.
class A{
Vector<packet> packetList;
A()
{
//packetList initialized here
}
void start_thread()
{
//start a thread here
}
void start_activity()
{
while(true)
{
//possibly sleep on semephore
//do work
}
}
}
You can access the Vector, provided you don’t iterate over it. If you Iterate over it, you need to hold a lock with
synchronizedon that object.If you want to queue “packets” of work, I suggest you look at using a BlockingQueue where you can wait for new tasks to be added, or use an ExecutorService which combines a Queue with a ThreadPool.