|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Abimaran Kugathasan wrote:And where is your main() method?
arjun srivastava wrote:
look below carefully in code.
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
arjun srivastava wrote:
also please tell me at line 14, d instance variable is static,so how can we able to access it from non-static method go()?
arjun srivastava wrote:
and if i remove static from line 14,it is giving me a java.lang.NullPointerException.
explain this please.
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
arjun srivastava wrote:
and please also tell me about the output part,i saw the previous thread ,but didn't get through.
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Abimaran Kugathasan wrote:
class Dudes {
static long flag=0;
synchronized void chat(long id) {
if(flag==0)
flag=id;
for(int i=1;i<3;i++) {
if(flag==id)
System.out.println("yo");
else
System.out.println("dude");
}
}
}
public class DudesChat implements Runnable {
static Dudes d;
void go() {
d=new Dudes();
new Thread(new DudesChat()).start();
new Thread(new DudesChat()).start();
}
public void run() {
d.chat(Thread.currentThread().getId());
}
public static void main(String[] args) {
new DudesChat().go();
}
}
[/code]
Here, you're passing Thread ID to your chat() method of Dudes object. And in the Dudes object, it's flag variable is initialized to 0. So, in the if condition, you reset it with your thread's ID. For the first thread, after set the flag variable to thread ID, both are same, so yo yo will be printed. And for the second thread, the Dudes's flag variable is set previous thread ID, so dude dude will be printed. And the chat() method is synchronized, one thread will invoke the method on Dudes object.
arjun srivastava wrote:
is it correct or what?
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Abimaran Kugathasan wrote:
arjun srivastava wrote:i have compile your code at least infinite times for me,but with chat() as synchronized.
output :
yo - 8
yo - 8
dude - 9
dude - 9
but it never shows yo dude dude yo with chat() as synchronized
which is the answer given in book.
hope you are getting me well this time.
SCJP6.0,My blog Ranchers from Delhi
arjun srivastava wrote:
but it never shows yo dude dude yo with chat() as synchronized
which is the answer given in book.
hope you are getting me well this time.
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|