在java中模拟线程间通信

时间:2017-02-05 07:03:33

标签: java multithreading

我创建了一个单例实例,我将在两个线程中获得一个线程,即AddEmployeeInfo将员工详细信息添加到ArrayList中并通知另一个线程,即DisplayEmployeeInfo,它显示添加的所有员工信息和然后等待进一步的数据, 请帮助我,我应该包括哪些更改,以使其正常工作并正在进行正确的线程间通信:

class AddEmployeeInfo implements Runnable{
SingletonInstance inst;
public AddEmployeeInfo(SingletonInstance instance) {
inst = instance;
}
 @Override
   public void run() {
Employee e1 = new Employee();
 e1.setEmpId(001);
 e1.setEmpName("SK");
e1.setEmpExp(2);
inst.addEmployee(e1);

  Employee e2 = new Employee();
  e2.setEmpId(002);
  e2.setEmpName("AMIT");
   e2.setEmpExp(3);
   inst.addEmployee(e2);
    } 
  }
 class DisplayEmployeeInfo implements Runnable{
    SingletonInstance inst;
  public DisplayEmployeeInfo(SingletonInstance instance) {
 inst = instance;
  }
  @Override
   public void run() {
   while(true){
   inst.displayEmployeeInfo();
     }}}
    public class EmployeeInfo {
    public static void main(String[] args) {
      SingletonInstance instance = new SingletonInstance();
       Thread t1 = new Thread(new AddEmployeeInfo(instance));
      Thread t2 = new Thread(new DisplayEmployeeInfo(instance));
        t1.start();
         t2.start();
         }
         }
        class SingletonInstance{
            public List<Employee> empDetails = new ArrayList<>();
             boolean flag = false;

             public synchronized void addEmployee(Employee emp){
          if (flag) {
           try {
             wait();
             } catch (InterruptedException e) {
             e.printStackTrace();
              }
             }
          flag = true;
             notify();
            empDetails.add(emp);
              }
             public synchronized void displayEmployeeInfo() {
           if (!flag) {
              try {
              wait();
             } catch (InterruptedException e) {
              e.printStackTrace();
            }
               }

           for(Employee getDetails : empDetails){
           System.out.println(getDetails.getEmpId() + " " +                 getDetails.getEmpName()); 
               }
             flag = false;
             notify();
           }
             }

0 个答案:

没有答案