0

我需要为以下内容创建一个 java 程序:

  1. 创建一个 ArrayList 来存储员工的姓名。
  2. 创建两个同步方法以将员工姓名添加到 ArrayList 并打印员工姓名。
  3. 两个线程完成添加员工后,打印员工姓名。

我已经完成了以下操作,但它不起作用。它在“pr.print(X)”行给出了一个例外。有人可以帮忙吗?这不是我的作业!!!我只是想学习。

import java.util.*;

public class Ch5Ex2 
 {
  public static void main(String[] args) 
   {
    List<String> li = new ArrayList<String>();
    Print pri = new Print();
    pri.start();
    Insert in = new Insert(li);
    in.start();
   }
}   

class Insert extends Thread
{
 Print pr = new Print();
 List<String> x;
 public Insert(List<String> x)
  {
    this.x = x;
  }

public synchronized void run()
 {
    try
    {
      x.add("robin");
      x.add("ravi");
      x.add("raj");
      pr.print(x);
    }
    catch(Exception e)
     {
        e.printStackTrace();
     }
 }

}

class Print extends Thread
{
 List<String> y;
public void print(List<String> y)
 {
    this.y = y;
    notify();
 }

public synchronized void run()
 {
    try
    {
     wait();
     for(int i=0;i<y.size();i++)
      {
         System.out.println(y.get(i));
      }
     }
    catch(Exception e)
    {
        e.printStackTrace();
    }
 }
}   
4

4 回答 4

2

我猜pr在课堂上是空的Insert,你永远不会调用构造函数。

于 2013-01-14T10:28:53.240 回答
2

我认为你需要这个:

import java.util.*;

public class Ch5Ex2 {
    public static void main(String[] args) {
        List<String> li = new ArrayList<String>();
        Print pri = new Print();
        pri.start();
        Insert in = new Insert(li, pri);
        in.start();
    }
}


class Insert extends Thread {
    Print pr;
    List<String> x;
    public Insert(List<String> x, Print p) {
        this.x = x;
        pr = p;
    }

    public synchronized void run() {
        try{
            x.add("robin");
            x.add("ravi");
            x.add("raj");
            pr.print(x);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

class Print extends Thread {
    List<String> y;
    public synchronized void print(List<String> y) {
        this.y = y;
        notify();
    }

    public synchronized void run() {
        try {
            while(y == null){
                wait();
            }
            for(int i=0;i<y.size();i++) {
                System.out.println(y.get(i));
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

现在这应该工作......

解决方案是:当您在创建方法中执行wait()此操作Print thread时,您必须对此进行操作。此外,如果在开始之前被调用,它将进入并且在这种情况下你不会这样做.. :)pri objectmain()notify()pri objectPrint threadnotify()Print threadyPrintnon-nullPrint threadwait()

于 2013-01-14T10:52:02.713 回答
0

你没有为 pr 分配内存。你只是在创建一个变量 Print pr。所以你必须得到 NPE

于 2013-01-14T10:33:27.627 回答
0

为了让您的生活更轻松,您可能会忘记应用程序级别的同步,而只需ArrayList通过调用Collections#synchronizedList()这样的方式创建同步

列出 yourArray = Collections.synchronizedList(new ArrayList())

在这种情况下,来自不同线程的所有调用都yourArray将被同步。除此之外,它看起来像prnull,因为您从不实例化它(感谢@Nikolay Kuznetsov)。

于 2013-01-14T10:32:35.310 回答