Hi!
I have a problem that I hope some of you can help me with.
I have a program that gets messages with socket communication. I want each message to be in a separate
thread and then I'm calling a synchronized method (for
test this method only do a System.out.println).
I thought that when you call a synchronized method it would be looked for other threads until the first thread had finished the method. But when I look in my log all threads have started the test method before the first one ends it.
I have included some of the code and the log (I have removed some of the System.out)
Would be very thankful if somebody can help me
/Jenny
// Main method, creates a new thread for each message from Socket
public static void main(
String args[])
{
Socket Client;
int i=0;
try
{
ServerSocket serverSocket=new ServerSocket(receiverPortName);
System.out.println("Waiting for message....");
while (true) {
Socket readSocket = serverSocket.accept();
readSocket.setKeepAlive(true);
System.out.println(readSocket.getKeepAlive());
Socket sendSocket=new Socket(sendServerName,sendPortName);
sendSocket.setKeepAlive(true);
new Thread(new ClientServicer(readSocket, sendSocket, i)).start();
i++;
}
}
catch (Exception e)
{System.out.println("error:" + e);}
}
// Run method, only call the test method
public synchronized void run(){
}
try {
test();
} catch(Exception exc){
System.err.println(exc.getMessage());
}
}
}
// test method
// Tells when the method start and stops and
// writes the threads name 20 times
public void test() throws InterruptedException{
System.out.println("*****Test************"+getName());
for (int i=0;i<20;i++){
System.out.println(getName());
}
sleep(10000);
//wait();
System.out.println("*****Test slut************"+getName());
}
// LOG FILE
Waiting for message....Thread-0
*****Test************Thread-0
Thread-0
Thread-0
Thread-0
Thread-0
Thread-0
Thread-0
Waiting for message....Thread-2
*****Test************Thread-2
Thread-2
Thread-2
Thread-2
Thread-2
Thread-2
Thread-2
Waiting for message....Thread-4
*****Test************Thread-4
Thread-4
Thread-4
Thread-4
Thread-4
Thread-4
Thread-4
*****Test slut************Thread-0
*****Test slut************Thread-2
*****Test slut************Thread-4