Java 这有什么意义?

Java 这有什么意义?,java,Java,今天我发现了一个很有趣的问题。如果删除System.out.println,基本上该代码不起作用。如果没有它,它永远不会进入if内部!!!(线程从主类开始) import java.util.LinkedList; 导入java.util.Vector; 导入java.util.Queue; 公共类匹配扩展了线程{ public static Vector onlinePlayers=new Vector(); public static Queue queuedPlayers=new Link

今天我发现了一个很有趣的问题。如果删除System.out.println,基本上该代码不起作用。如果没有它,它永远不会进入if内部!!!(线程从主类开始)

import java.util.LinkedList;
导入java.util.Vector;
导入java.util.Queue;
公共类匹配扩展了线程{
public static Vector onlinePlayers=new Vector();
public static Queue queuedPlayers=new LinkedList();
@凌驾
公开募捐{
while(true){
System.out.println(queuedPlayers.size());
if(queuedPlayers.size()>=2){
新的Matchmaking_GameFoundThreads(queuedPlayers.remove(),queuedPlayers.remove());
}
}
}
}

链接列表未同步

在一个线程中对它所做的更改在另一个线程中可能不可见。尝试使用:

public static List<Player> queuedPlayers = 
     Collections.synchronizedList( new LinkedList<Player>() );
公共静态列表队列层=
Collections.synchronizedList(新的LinkedList());

我通过使队列变得易变来解决这个问题。
我不确定这样做是否有好处,因为我不熟悉volatile的用法,但它确实有效…

并发或调试问题?确切地说,
size()
做什么?返回排队的玩家数量(游戏中的代码)。因此,每次队列中有2+个玩家时,它都会将他们相互匹配调用
System.out.println
的原因是,当
queuedPlayers
是非易失性的时,调用
PrintStream
的底层方法是同步的,这有效地强制从主内存而不是缓存中获取
queuedPlayers
的值。的公认答案给出了一个深入的解释。
public static List<Player> queuedPlayers = 
     Collections.synchronizedList( new LinkedList<Player>() );