Java - Synchronized
Hi i have made a something that extends thread that adds adds an object
that has a IP in it. then i made two instances of this thread and started
them. they use the same list.
I now want to use Synchronized to stop the concurrent update problem. But
its not working and i cant work out why.
My main class:
import java.util.*;
import java.io.*;
import java.net.*;
class ListTest2{
public static LinkedList<Peer> myList = new LinkedList<Peer>();
public static void main(String [] args){
try{
AddIp test1 = new AddIp(myList);
AddIp test2 = new AddIp(myList);
test1.start();
test2.start();
}
catch(Exception e){System.out.println("not working");}
}
}
My thread class:
class AddIp extends Thread{
public static int startIp =0;
List<Peer> myList;
public AddIp(List<Peer> l){
myList = l;
}
public synchronized void run() {
try{
startIp = startIp+50;
int ip = startIp;
InetAddress address = InetAddress.getByName("127.0.0.0");
Peer peer = new Peer(address);
while(ip <startIp+50){
ip++;
address = InetAddress.getByName("127.0.0."+ip);
peer = new Peer(address);
myList.add(peer);
if(myList.indexOf(peer)== (myList.size() -1)){}
else{System.out.println("Lost"+peer.peerIp);}
}
}catch(Exception e){}
}
}
Can anyone help me out here im lost for ideas thanks.
No comments:
Post a Comment