• Post Reply Bookmark Topic Watch Topic
  • New Topic

synchronized

 
abalfazl hossein
Ranch Hand
Posts: 635
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator







I am leaning thread in JAVA

The result of this program in to know difference between synchronized
method and unsynchronized mrthod

At this case ,Because I don't use synchronized
it must not print out error.

because threads run at same time.

But it prints : ERROR

why?

Another question is:

When I trace this program line by line ,

after lines , it goes to this line :


I want to know why after it arrives this line:

thread1.start();

Why it doesn't go to deduct class and it goes to this line :

thread2.start();

Thanks in advance



 
Vijitha Kumara
Bartender
Posts: 3952
21
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
abalfazl hossein wrote:At this case ,Because I don't use synchronized it must not print out error.

Why? It's possible since no synchronization in the method "deductaccount()". Both threads may decrement the amount if the context switching happens when both of them are inside the method.
 
abalfazl hossein
Ranch Hand
Posts: 635
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think that this program must work line this ( If i am wrong please make me correct):

1-


Thread1 starts, after that , this code will be run :




After that ,Because of this line :a.deductaccount(100); this code will run:



Ok, Now total become 0,

at the same time thread2 has started, and value of total become -100.Then the program must print ERROR

If i don't understadn or cann't trace, Please guide me




 
Vijitha Kumara
Bartender
Posts: 3952
21
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
abalfazl hossein wrote:at the same time thread2 has started, and value of total become -100.Then the program must print ERROR

We don't know that exactly as it's up to the JVM to pick which thread should execute at a given time. So you may not even see that message ever as this is pretty small program one thread may finish even before other thread enters the method. So there's no guarantee how those threads will be executing.
 
abalfazl hossein
Ranch Hand
Posts: 635
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks, still work on it
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!