如何使用Java线程在“列表”中插入项目?

时间:2015-01-08 02:33:08

标签: java multithreading

使用以下程序,Java不允许在线程中使用非最终变量来避免"数据竞争"与C ++ 11不同,这是有道理的。将synchronized关键字与insertFront()一起使用也无法确保j的正确值会在列表中插入。

public class Dummy2 {
    public static void main(String[] args) throws InterruptedException {
        final SList list = new SList();
        for(Integer j = 0; j < 10; j++){
            Thread t = new Thread(new Runnable(){
                public void run(){
                    list.insertFront(j);
                }
            });
            t.start();
        }

        // not sure, how to join the threads with above code.
        for(int i = 1; i <= 10; i++){
            Object obj = list.nth(i);
            System.out.println(obj);
        }

    }
}

可以使final Integer k = j;的值不一致

这是class SList

中的insertFront()操作
public synchronized void insertFront(Object obj) {
    head = new SListNode(obj, head);
    size++;
  }

这是nth()方法

 public Object nth(int position) {
    SListNode currentNode;
    if ((position < 1) || (head == null)) {
      return null;
    } else {
      currentNode = head;
      while (position > 1) {
        currentNode = currentNode.next;
        if (currentNode == null) {
          return null;
        }
        position--;
      }
      return currentNode.item;
    }
  }

  SList() {
    size = 0;
    head = null;
  }

截至目前,请不要鼓励我使用现有的Java包。

请告诉我,在SList中如何使用上述程序中具有一致值的线程进行插入操作?

注意:多线程新手

1 个答案:

答案 0 :(得分:1)

  

Java不允许在线程中使用非final变量来避免   “数据竞赛”

这是错误的。它告诉你使用final变量,因为你是在一个匿名的内部类(你的Runnable)中引用它。

此外,最终与否,你的SList永远不会被实例化,因此你的问题。尝试更改

final SList list = null;

final SList list = new SList();

反正什么是SList