4
I have the following code snippet:
class classe{
public static void main(String[] args){
Integer lock = 0;
Thread t1 = new Thread(){
public void run(){
// instruções thread sem sincronia
synchronized(lock){
//instruções sincronizadas
}
// instruções thread sem sincronia
}
}
Thread t2 = new Thread(){
public void run(){
// instruções thread sem sincronia
synchronized(lock){
//instruções sincronizadas
}
// instruções thread sem sincronia
}
}
t1.start();
t2.start();
}
}
I would like to know how the variable works lock
as whole in that code snippet, what happens to it when it enters the block synchronized
.
What I need in my program is that when the first thread starts executing one part of an instruction block, the other is locked when arriving in a block synchronized
related to the first.
EDIT: Making clearer the problem I have, I need to communicate several threads that will run at the same time using Wait() and notify(), the example below better exemplifies the problem:
class classe{
public static void main(String[] args){
Integer lock1 = new Integer(0);
Integer lock2 = new Integer(1);
Thread t1 = new Thread(){
public void run(){
// instruções thread sem sincronia
synchronized(lock1){
//instruções sincronizadas
lock1.notify();
}
// instruções thread sem sincronia
}
}
Thread t2 = new Thread(){
public void run(){
// instruções thread sem sincronia
synchronized(lock1){
//instruções sincronizadas
while(condicao)
lock1.wait();
}
// instruções thread sem sincronia
}
}
Thread t3 = new Thread(){
public void run(){
// instruções thread sem sincronia
synchronized(lock2){
//instruções sincronizadas
while(condicao)
lock2.wait();
}
// instruções thread sem sincronia
}
}
t1.start();
t2.start();
t3.start();
}
}
By my understanding of the above program, while thread 1 and thread 2 are synchronized, thread 3 can be run independently of both. The thinking is right?
Yes, thread 3 is "independent" because it uses a different lock than 1 and 2 (these in turn use the same lock and are synchronized). But there is no reason to use Integer, could be two Object even
– hkotsubo
I don’t do much with the Wait() and notify() primitives so I can’t be sure the syntax is correct, the code looks ok but I’m not seeing lock2.notify() code anywhere to notify thread 3, it will sleep indefinitely. But I think it’s better instead of you describing a possible solution describe your problem and we see how it could be solved.
– Piovezan
On another question in the case.
– Piovezan