1ftw1
1ftw1

Reputation: 666

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.

Upvotes: 0

Views: 145

Answers (4)

mcr619619
mcr619619

Reputation: 435

You'd be better off implementing Runnable oppose to extending thread

also

public void run() {
  synchronize(list){
   //stuffs
  }
}

Upvotes: 1

Bex
Bex

Reputation: 2925

The easiest way is to use a List implementation that can handle multiple threads. Try CopyOnWriteArrayList.

Upvotes: 0

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

they use the same list.

You can try to use Vector instead List. Vector is synchronized

or set your List to be synchronized:

List myList = Collections.synchronizedList(myList);

instead to use:

synchronize(myList){

 } 

Upvotes: 0

rocketboy
rocketboy

Reputation: 9741

 public synchronized void run() 

Synchronizes on calling instance: this.

So, 1st thread synchronizes on test1 and 2nd thread synchronizes on test2, which doesn't help at all.

You want to synchronize on the shared resource, in this case: myList

public void run() {
  synchronize(myList){
   //your Logic
  }
}

As a side note: Implement runnable instead of extending a Thread. Read more here.

Upvotes: 5

Related Questions