1ft*_*tw1 0 java multithreading synchronization
嗨,我做了一个扩展线程的东西,添加添加一个具有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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的线程类:
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) {
}
}
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮助我在这里我失去了想法谢谢.
public synchronized void run()
Run Code Online (Sandbox Code Playgroud)
在调用实例上同步:this.
因此,第一个线程在test1上同步,第二个线程在test2上同步,这根本没有帮助.
您希望在共享资源上进行同步,在这种情况下: myList
public void run() {
synchronize(myList){
//your Logic
}
}
Run Code Online (Sandbox Code Playgroud)
作为旁注:实施runnable而不是扩展Thread.在这里阅读更多.
| 归档时间: |
|
| 查看次数: |
136 次 |
| 最近记录: |