gpt4 book ai didi

Java——同步

转载 作者:行者123 更新时间:2023-12-01 08:09:19 29 4
gpt4 key购买 nike

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

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

我的主要类(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");
}
}
}

我的线程类:

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

任何人都可以帮我吗,我失去了想法,谢谢。

最佳答案

 public synchronized void run() 

在调用实例时同步:this

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

您想要同步共享资源,在本例中为:myList

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

附注:实现runnable而不是扩展Thread。了解更多 here .

关于Java——同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18810193/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com