今天我发现了一个很有趣的问题。基本上,如果您删除System.out.println,此代码将不起作用。如果没有它,它永远不会进入if!(线程从主类启动)
import java.util.LinkedList;
import java.util.Vector;
import java.util.Queue;
public class Matchmaking extends Thread{
public static Vector onlinePlayers = new Vector();
public static Queue<Player> queuedPlayers = new LinkedList<Player>();
@Override
public void run() {
while(true){
System.out.println(queuedPlayers.size());
if(queuedPlayers.size() >= 2){
new Matchmaking_GameFoundThreads(queuedPlayers.remove(),queuedPlayers.remove());
}
}
}
}发布于 2015-08-08 07:33:05
LinkedList未同步。
在一个线程中对它所做的更改可能在另一个线程中不可见。尝试使用:
public static List<Player> queuedPlayers =
Collections.synchronizedList( new LinkedList<Player>() );发布于 2015-08-08 07:45:39
我通过将队列设置为volatile解决了这个问题。我不确定这样做是否好,因为我不熟悉volatile的用法,但它很有效……
https://stackoverflow.com/questions/31887938
复制相似问题