0

嗨,我做了一个扩展线程的东西,它添加了一个包含 IP 的对象。然后我制作了这个线程的两个实例并启动了它们。他们使用相同的列表。

我现在想使用 Synchronized 来停止并发更新问题。但它不起作用,我不知道为什么。

我的主要课程:

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");
        }
    }
}

我的线程类:

 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) {
        }
    }
}

任何人都可以在这里帮助我,我失去了想法,谢谢。

4

4 回答 4

5
 public synchronized void run() 

在调用实例上同步:this

因此,第一个线程在 test1 上同步,第二个线程在 test2 上同步,这根本没有帮助。

您想在共享资源上同步,在这种情况下:myList

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

附带说明:实施runnable而不是扩展Thread. 在这里阅读更多。

于 2013-09-15T07:58:12.837 回答
1

你最好实现 Runnable 反对扩展线程

public void run() {
  synchronize(list){
   //stuffs
  }
}
于 2013-09-15T08:20:28.347 回答
0

他们使用相同的列表。

您可以尝试Vector改用List. Vector是同步的

或将您List的设置为同步:

List myList = Collections.synchronizedList(myList);

改为使用:

synchronize(myList){

 } 
于 2013-09-15T08:01:47.507 回答
0

最简单的方法是使用可以处理多个线程的 List 实现。试试 CopyOnWriteArrayList。

于 2013-09-15T08:06:07.620 回答