我需要为以下内容创建一个 java 程序:
- 创建一个 ArrayList 来存储员工的姓名。
- 创建两个同步方法以将员工姓名添加到 ArrayList 并打印员工姓名。
- 两个线程完成添加员工后,打印员工姓名。
我已经完成了以下操作,但它不起作用。它在“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();
    }
 }
}