| Author |
what's wrong with my code?about synchronized,please help me.
|
Tu Ran
Ranch Hand
Joined: Feb 09, 2002
Posts: 30
|
|
public class Thread1 extends Thread{ int threadNumber; Thread1(int xx){ threadNumber=xx; } public static void main(String[]args){ Thread1 obj1=new Thread1(1); Thread1 obj2=new Thread1(2); obj1.start(); obj2.start(); System.out.println("Main ends");} public void run(){ synchronized(this){ //why outcome can't synchronized? for(int i=10;i>0;i--){ System.out.println("Thread = "+threadNumber); } } } }
|
Enjoy java,enjoy life
|
 |
Rajinder Yadav
Ranch Hand
Joined: Jan 18, 2002
Posts: 178
|
|
Your program creates two objects that run independently on separate threads, each has it own field "threadNumber". Do you understand what the synchronized keyword does? It is suppose to sync access to shared resources, in your code there is nothing shared that need to be synchronized! It's a good idea to always state what you are trying to achieve, otherwise no one can help you! Simple asking what's wrong is not helpful
|
<a href="http://www.rajindery.com" target="_blank" rel="nofollow">Rajinder Yadav</a><p>Each problem that I solved became a rule which served afterwards to solve other problems. --Rene Descartes
|
 |
Tu Ran
Ranch Hand
Joined: Feb 09, 2002
Posts: 30
|
|
OH,my god~~~ i made a big mistake,i see you mean~~thanks a lot Rajinder Yadav ;I will study and think hard by myself . you know i just study java three month,now preparing SCJP ok~~thanks again
|
 |
Rajinder Yadav
Ranch Hand
Joined: Jan 18, 2002
Posts: 178
|
|
Threading can be a very difficult concept to master, I know when I started it took me a very long time. Three months may or may not be a very long time depending on your background! I have been playing around with java from about a month now, off-and-on, so you're ahead of me by two months But keep at it and have fun!
|
 |
 |
|
|
subject: what's wrong with my code?about synchronized,please help me.
|
|
|