如何在“中插入项目”;SList";使用Java线程?

如何在“中插入项目”;SList";使用Java线程?,java,multithreading,Java,Multithreading,在下面的程序中,Java不允许在线程中使用非最终变量来避免“数据竞争”,这与C++11不同,C++11是有意义的。将synchronized关键字与insertFront()一起使用也无法确保j的正确值将被插入列表中 public class Dummy2 { public static void main(String[] args) throws InterruptedException { final SList list = new SList();

在下面的程序中,Java不允许在线程中使用非最终变量来避免“数据竞争”,这与C++11不同,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);
        }

    }
}

下面是n()方法

到目前为止,请不要鼓励我使用现有的Java包

请让我知道,如何使用上述程序中具有一致值的线程在
SList
中执行插入操作

注意:多线程是新的

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

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

此外,不管是否为final,您的SList永远不会被实例化,因此您的问题也不会被实例化。试着改变

final SList list = null;


还有什么是
SList
呢?

等等,有什么问题吗?很明显,
insertFront()
操作不起作用,因为
SList
声明为
final
展开此操作。@SotiriosDelimanolis抱歉混淆,请惩罚我。请查看查询编辑。您正在尝试进行并发编程,但您没有保护您的关键部分。当然有,为什么您认为不会?此外,您还需要区分线程和
线程
对象。而且,您没有显示
的定义,也没有显示它的实例化位置(或是否)。
 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;
  }
final SList list = null;
final SList list = new SList();