【问题标题】:Java Swing - How to synchronize ArrayLists [closed]Java Swing - 如何同步 ArrayLists [关闭]
【发布时间】:2014-11-27 22:11:19
【问题描述】:

我正在尝试跨两个不同线程访问单个列表。最初,我使用的是 for 循环,如下所示:

for (int i = 0; i<fighterList.size(); i++) {
    if (fighterList.get(i).isDestroyed() == true) fighterList.remove(i);
}

然而,我被告知我必须同步线程。我不太明白如何做到这一点,更重要的是它是如何工作的。到目前为止,我咨询过的资源似乎指向了两种不同的方法:

synchronized(fighterList) {
    for (Object o : fighterList) {
        o.doSomeMethod();
    }
}

Iterator<Fighter> iterator = fighter.iterator(); 
while (iterator.hasNext())
    if (iterator.next().returnSomething() == false) iterator.next().doSomeMethod();
}

然而,这些似乎都不起作用。执行此操作的“正确”方法是什么,是否有更好的文档可用?

【问题讨论】:

  • “这些似乎都不起作用”不是问题描述。您需要描述您想要实现的行为以及您得到的结果。还包括short but full code which will let us reproduce your problem
  • 即使没有多个线程访问fighterList,第一个示例也会失败,因为它在迭代列表时修改了列表,这是被禁止的!
  • 您可以使用synchronized 包装器进行包装,请参阅Collections.synchronizedList
  • @MadProgrammer 如果我没记错的话synchronizedList 使单个操作成为原子操作(添加、包含、删除...),因此 OP 还需要为这些操作集提供单独的同步。根据 OP 真正想要实现的目标, CopyOnWriteArrayList 也可能是一种选择。无论如何,要回答这个问题,我们(或至少我)需要更多信息。
  • @Pshemo 是的,因为缺少上下文 ;) - 此外,根据具体情况,同步操作可能会更好(调用的方法)......但上下文为王 ;)跨度>

标签: java swing arraylist synchronized


【解决方案1】:

嗯,当你想要一个线程安全的代码时,你通常会同步, 意思是当这个线程进入 cpu 时没有其他线程 也会尝试到达那里,这也称为“获取对象锁定”, “获取锁”、“锁定对象”或“同步对象” 当然,你应该永远记住,作为 Java 设计师,没有什么是可以保证的 经常说.. 无论如何,为了运行一个线程并将其同步到包含该线程的类 应该做以下两者之一: 1.扩展Thread类 或者 2.实现Runnable接口。 此类还应覆盖在 Thread 类中定义的抽象方法 在名为“public void run(){}”的 Runnable 接口中, 它实际上充当线程的“主”类。

让我们稍微解决一下。这比听起来容易得多:

class ThreadPractice implements Runnable{

 @override   //This annotation denotes that it overrides an abstract method from
             // the Runnable interface.
     public void run(){ // We've promised

      coutingStuff() ; // Calling the synchronized method from the run() method.

         }

      public void synchronized coutingStuff(){// now this is a synchronized method...

              for(int i=0; i<100; i++){// Creating a for loop that counts from 0 to 99...

               System.out.println("this is the "+i+" time that this loop runs");

                // Now, putting the thread to sleep for 1 second:


               try{
                    Thread.sleep(1000);

                     }catch(InterruptedException iex){

                         System.out.println(iex.getMessage());
                      }
               }// End for loop
       }// End public void synchronized coutingStuff(){....


          public static void main(String[] args){

             //Now creating a thread object:

             Runnable rnb = new ThreadPractice();
              Thread count = new Thread(rnb);
                 count.start(); // starts the thread that contains
                                 // the synchronized method.

                }// End main



        }// End of class ThreadPractice

我强烈建议您阅读有关线程的章节 在 KS&BB 指南中,您可以在此处下载: http://firozstar.tripod.com/_darksiderg.pdf

【讨论】:

  • 但是synchronized方法不是根据类的实例锁定的吗?
猜你喜欢
  • 2021-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多