Solved

Two threads Hang the program

Posted on 2003-11-14
18
550 Views
Last Modified: 2008-02-01
Hello

I always has problems with multiple threads in Java. Now i am writing a java program. I have two thread classes in my application. Here is how they operate

- Main program creates one instance of each thread class and set it running. Also pass itself as argument so threads can call public methods of main program
- main program also make public some of its methods which are Synchronized. Both threads can access shared data. maipulate it and also refreshes the GUI of main program.
- Both threads keep monitoring any takes in the Tasks collection and if there is any it remote it from collection and perform it. In the execution both threads access the shared data through Synchronized Public methods of main program.
- SO both threads implements     While(True) {  }   and keep waitching the tasks collection for any tasks. both threads stop only when the main program is terminated.

OKey now the probelm .... after some time the GUI of the main program seems to be HANG. nothing happens.  and i have force to stop the program. I tried every thing like place a random sleep in the while loop of threads Nothing.

Well when i run the program with only thread then it seems to work fine but with two threads program hands.

Below is the implementation of one thread class. other thread class is almost same with minor difference

Shahzad Aslam





class BorrowThread implements Runnable
{
      Thread thread;
      Ass mainApp;
      LibraryTask LibTask;
      Random RndNum;

      public BorrowThread(Ass s)
      {
            thread = new Thread(this);
            thread.start();
            mainApp = s;

            RndNum = new Random( System.currentTimeMillis() );
      }


      public void run()
      {
            int temp;
            DVD dvd;

            while(true)
            {
                  LibTask = mainApp.getDVDIssueTask();
                  if(LibTask != null)
                  {
                              dvd = mainApp.getDVD(LibTask.DVDSerialNo, 1);
                              dvd.StudentNo = LibTask.StudentID;
                              mainApp.refreshList(1);
                              mainApp.addDVD(dvd, 2);
                              mainApp.refreshList(2);
                              mainApp.addHistory("DVD    " + dvd.Name + "    has been issued to    " + mainApp.getStudentName(LibTask.StudentID));
                  }
                  try
                  {
                        thread.sleep(RndNum.nextInt(150) + RndNum.nextInt(15));
                  }catch(Exception e){}

            }
      }
}


0
Comment
Question by:shahzad73
  • 6
  • 5
  • 3
  • +2
18 Comments
 
LVL 35

Expert Comment

by:TimYates
ID: 9747373
I think you would be better off using wait and notify...

can you post all the code?  I will try and help you get it set up...

Tim.
0
 
LVL 15

Expert Comment

by:dualsoul
ID: 9747428
hm...it seems like producer/consumer task, who creates DVDtasks, for this threads? please post this code.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 9747467
Hee hee, isn't that what I said? ;-)
0
 
LVL 7

Expert Comment

by:grim_toaster
ID: 9747480
As stated by the other two, we will need more of the code, but there are a few problems with what you've posted (but probably nothing to do with the problem):

You don't need to maintain an instance reference to your created Thread, as you do not need to do thread.sleep(..), as the sleep method is static, and will always sleep the current thread.  (but I do agree with TimYates, that you would be better off with wait/notify).

Before you start the thread in the constructor, you should set up all of the required variables, so your constructor would look like:

public BorrowThread(Ass s)
     {
          Thread thread = new Thread(this);
          mainApp = s;
          RndNum = new Random( System.currentTimeMillis() );
          thread.start();
     }

As you may get into a situation where it will try to read the varibles before they have been set.

In addition to that, do you really want to run the start the Thread in the constructor?  You're class implements Runnable, so whatever uses your class should really handle the starting of the Thread.

-- Main program creates one instance of each thread class and set it running
If this is so, then you've created and started two threads for each instance of your class.


0
 
LVL 7

Expert Comment

by:grim_toaster
ID: 9747531
Ah, in fact I think I may know why it seems to hang.  What you've got is effectively an infinite loop (while(true)), and your sleeping calls are for only a fraction of a second (sleep takes the number of milliseconds as a parameter, and your random calls return a number less than 1 second (I believe anything upto about 165ms), so your loop will keep running.

If you implement some form of wait/notify implementation, then the thread will only do what it is supposed to do when something has been added to your list, instead of several times per second.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 9747542
:-)
0
 
LVL 7

Expert Comment

by:grim_toaster
ID: 9747544
Indeed, the API document for nextInt() states:

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive),

so your possible values are 0 - 165ms.

But you may still have other problems with locking...
0
 
LVL 15

Expert Comment

by:dualsoul
ID: 9747648
> Hee hee, isn't that what I said? ;-)
;) seems so :)
0
 
LVL 1

Author Comment

by:shahzad73
ID: 9747836

Well here is the whole code. This is a assignment which requires to use Threads and Monitors. Just copy the whole code in a text file and save it as Ass.java. compile it and run it.

You will have a GUI.  First List has some DVD's to issue. select a DVD. Click Borrow. Select a student. and click OK. this will issue the DVD to the student. what happen at the point when you click OK is that it generates task. This task it pick up by the BorrowThread. here are the step the Borrow thread do.

- get the DVD object from DVDList Vector. and delete it from it.
- Add DVD obejct to the BorrowedDVDList Vector.
- Refresh List DVD and DVD will not be in the list
- Refresh List Borrowed DVD which will has the DVD just issued


Select the DVD in the Borrowed List and Click the Return button
This will create the Return DVD task which will be pack up by the ReturnThread and process the same way as above only in reverse.




Okey run the program.. jsut issue some DVD's. Return DVD's keep doing and very thing seems to work fine. Then Suddenly when you RETURN A DVD the program ............H A N G S............


Shahzad



import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;



public class Ass  extends Frame implements ActionListener
{
    //JOptionPane.showMessageDialog(this, "Message", "Title", JOptionPane.INFORMATION_MESSAGE);                  

    JButton buttonBorrow;
    JList listDVD;
    JScrollPane sp_listDVD;
    JLabel labelDVD;
    JList listWaiting;
    JScrollPane sp_listWaiting;
    JList listBorrow;
    JScrollPane sp_listBorrow;
    JButton buttonReturn;
    JList listHistory;
    JScrollPane sp_listHistory;
    JLabel labelBorrow;
    JLabel labelWaiting;
    JLabel labelDVD2;
    JLabel labelBorrow2;
    JLabel labelWaiting2;

    DefaultListModel listModel_listDVD;
    DefaultListModel listModel_listWaiting;
    DefaultListModel listModel_listBorrow;
    DefaultListModel listModel_listHistory;




   
    Student student;                  //A object of Student
    DVD dvd;                        //A object of DVD

    Vector DVDList;                  //This will be a collection of DVD's available in library.
                                        //This is collection of Student object

    Vector BorrowedDVDList;

    public Vector StudentList;      //This is a list of students. This is a collection of DVD
                                    //object

    Vector  WaitingList;            //This a waiting student list. A new student waiting
                                    //student waiting for a DVD will be added at the end of       
                                    //the collection. When a DVD is available then preference
                                    //will be given to a student at the top of this list. This       
                                    //is a collection of Student Object
   
    Enumeration enum;                  //This enumeration will be used to loop through the above Vector objects collection.

   
    LibraryTask LibTask;                  //A single library task object
    Vector LibraryTasksList;            //When a DVD is issued to a student, that task is added to this
                                    //collection. similarly when a DVD is return by a student, that task is
                                    //is also added to this collection. Both IssueThread and ReturnThread monitor this
                                    //collection, remove their relavent tasks from collection and then perform them.
                                    //This is a collection of LibraryTask objects
   

    JDialog dialog;

    SelStudent selectStudentWindow;      //This select student window


    BorrowThread borrowThread;
    ReturnThread returnThread;



    public Ass()
    {
        GUIFileLayout customLayout = new GUIFileLayout();
       



        setFont(new Font("Helvetica", Font.PLAIN, 12));
        setLayout(customLayout);



        buttonBorrow = new JButton("Borrow");
        buttonBorrow.setActionCommand("Borrow");
        buttonBorrow.addActionListener(this);
        add(buttonBorrow);


      
        listModel_listDVD  = new DefaultListModel();
        listModel_listWaiting  = new DefaultListModel();
        listModel_listBorrow  = new DefaultListModel();
        listModel_listHistory = new DefaultListModel();

       
        listDVD = new JList(listModel_listDVD);
        sp_listDVD = new JScrollPane(listDVD);
        add(sp_listDVD);

        labelDVD = new JLabel("Available DVD's");
        add(labelDVD);

        listWaiting = new JList(listModel_listWaiting);
        sp_listWaiting = new JScrollPane(listWaiting);
        add(sp_listWaiting);

        listBorrow = new JList(listModel_listBorrow);
        sp_listBorrow = new JScrollPane(listBorrow);
        add(sp_listBorrow);

        buttonReturn = new JButton("Return");
        buttonReturn.setActionCommand("Return");
        buttonReturn.addActionListener(this);
        add(buttonReturn);

        listHistory = new JList(listModel_listHistory);
        sp_listHistory = new JScrollPane(listHistory);
        add(sp_listHistory);

        labelBorrow = new JLabel("Borrow DVD");
        add(labelBorrow);

        labelWaiting = new JLabel("Waiting List");
        add(labelWaiting);

        labelDVD2 = new JLabel("label_1");
        add(labelDVD2);

        labelBorrow2 = new JLabel("label_2");
        add(labelBorrow2);

        labelWaiting2 = new JLabel("label_3");
        add(labelWaiting2);

        setSize(getPreferredSize());

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });



        DVDList = new Vector();            
        BorrowedDVDList = new Vector();
        StudentList = new Vector();                        
        WaitingList = new Vector();            
        LibraryTasksList = new Vector();



        dvd = new DVD();       
        dvd.SerialNo = 1;                        //Serial No of DVD
        dvd.Name = "National Geographics";      //name of DVD;
        dvd.StudentNo = 0;                        //DVD is not yet issued to any student so StudentNo will be 0                  
        DVDList.addElement(dvd);                              

        dvd = new DVD();       
        dvd.SerialNo = 2;                        //Serial No of DVD
        dvd.Name = "Atlantic Dive";                  //name of DVD;
        dvd.StudentNo = 0;                        //DVD is not yet issued to any student so StudentNo will be 0                  
        DVDList.addElement(dvd);                              

        dvd = new DVD();       
        dvd.SerialNo = 3;                        //Serial No of DVD
        dvd.Name = "Africa Direct";                  //name of DVD;
        dvd.StudentNo = 0;                        //DVD is not yet issued to any student so StudentNo will be 0                  
        DVDList.addElement(dvd);                              

        dvd = new DVD();       
        dvd.SerialNo = 4;                        //Serial No of DVD
        dvd.Name = "Singapore Roars";            //name of DVD;
        dvd.StudentNo = 0;                        //DVD is not yet issued to any student so StudentNo will be 0                  
        DVDList.addElement(dvd);                              
        
      
       enum = DVDList.elements();
       while(enum.hasMoreElements())
       {
            dvd = (DVD)(enum.nextElement());
            listModel_listDVD.addElement(dvd.Name);            
       }


      student = new Student();
      student.SNo = 1;
      student.Name = "Andy Aiken";
      StudentList.addElement(student);

      student = new Student();
      student.SNo = 2;
      student.Name = "Allan Bruce";
      StudentList.addElement(student);

      student = new Student();
      student.SNo = 3;
      student.Name = "Gordon Christie";
      StudentList.addElement(student);

      student = new Student();
      student.SNo = 4;
      student.Name = "Gary Ewing";
      StudentList.addElement(student);

      student = new Student();
      student.SNo = 5;
      student.Name = "David Fowler";
      StudentList.addElement(student);
      
      student = new Student();
      student.SNo = 6;
      student.Name = "Qiang Huo";
      StudentList.addElement(student);

      student = new Student();
      student.SNo = 7;
      student.Name = "Adil Hameed";
      StudentList.addElement(student);


      student = new Student();
      student.SNo = 8;
      student.Name = "Qiang Huo";
      StudentList.addElement(student);


      student = new Student();
      student.SNo = 9;
      student.Name = "Honghai Liu";
      StudentList.addElement(student);


      student = new Student();
      student.SNo = 10;
      student.Name = "Ying Liu";
      StudentList.addElement(student);


      student = new Student();
      student.SNo = 11;
      student.Name = "Mairi McCallum";
      StudentList.addElement(student);


      selectStudentWindow = new SelStudent();
      borrowThread = new BorrowThread(this);
      returnThread = new ReturnThread(this);
    }


    public void actionPerformed(ActionEvent e)
    {
                if ("Borrow".equals(e.getActionCommand()))
            {
                  if(listDVD.getSelectedIndex() == -1)
                        JOptionPane.showMessageDialog(this, "Please select a DVD to Issue", "Select DVD", JOptionPane.INFORMATION_MESSAGE);
                  else
                  {      
                      selectStudentWindow .setTitle("Issue DVD");
                      selectStudentWindow .pack();
                      selectStudentWindow.show();
                  }
                }
            else
            {
                  if(listBorrow.getSelectedIndex() == -1)
                        JOptionPane.showMessageDialog(this, "Please select a DVD to return", "Select DVD", JOptionPane.INFORMATION_MESSAGE);                  
                  else
                  {            
                        //Generate the Return DVD task
                        LibTask = new LibraryTask();
                        LibTask.TaskID = false;
                        dvd = (DVD)BorrowedDVDList.elementAt(listBorrow.getSelectedIndex());
                        LibTask.DVDSerialNo = dvd.SerialNo;
                        LibraryTasksList.addElement(LibTask);
                  }
            }
    }



    public synchronized LibraryTask getDVDIssueTask()
    {
        int temp;       

        for(temp=0;temp<LibraryTasksList.size();temp++)
        {
            LibTask = (LibraryTask)LibraryTasksList.elementAt(temp);
            if(LibTask.TaskID == true)
            {
                  LibraryTasksList.removeElementAt(temp);
                  return LibTask;
            }                               
        }
      return null;
    }




    public synchronized LibraryTask getDVDReturnTask()
    {
        int temp;

        for(temp=0;temp<LibraryTasksList.size();temp++)
        {
            LibTask = (LibraryTask)LibraryTasksList.elementAt(temp);
            if(LibTask.TaskID == false)
            {
                  LibraryTasksList.removeElementAt(temp);
                  return LibTask;
            }                               
        }
      return null;
    }


      public synchronized void addHistory(String s)
      {
            listModel_listHistory.addElement(s);
      }



      public synchronized DVD getDVD(int SNO, int ListID)
      {
            int temp;

            if(ListID == 1)
            {
                  for(temp=0;temp<DVDList.size();temp++)
                  {
                        dvd = (DVD)DVDList.elementAt(temp);
                        if(dvd.SerialNo == SNO)
                        {
                              DVDList.removeElementAt(temp);
                              return dvd;                        
                        }
                  }
            }
            else if(ListID == 2)
            {
                  for(temp=0;temp<BorrowedDVDList.size();temp++)
                  {
                        dvd = (DVD)BorrowedDVDList.elementAt(temp);
                        if(dvd.SerialNo == SNO)
                        {
                              BorrowedDVDList.removeElementAt(temp);
                              return dvd;                        
                        }
                  }
            }
            return null;
      }



      public synchronized void addDVD(DVD dvd, int ListID)
      {
            if(ListID == 1)
                  DVDList.insertElementAt(dvd, 0);
            else if(ListID == 2)
                  BorrowedDVDList.insertElementAt(dvd, 0);                  
      }





      public synchronized void refreshList(int ListID)
      {
            if(ListID == 1)
            {
                  while(listModel_listDVD.size() > 0)
                        listModel_listDVD.removeElementAt(0);

                   enum = DVDList.elements();
                   while(enum.hasMoreElements())
                   {
                        dvd = (DVD)(enum.nextElement());
                        listModel_listDVD.addElement(dvd.Name);            
                   }
            }
            else if(ListID == 2)
            {
                  while(listModel_listBorrow.size() > 0)
                        listModel_listBorrow.removeElementAt(0);


                   enum = BorrowedDVDList.elements();
                   while(enum.hasMoreElements())
                   {
                        dvd = (DVD)(enum.nextElement());
                        listModel_listBorrow.addElement(dvd.Name);            
                   }
            }
            else if(ListID == 3)
            {

            
            }
      }



      public synchronized String getStudentName(int SNo)
      {
            Student student;
            int temp;
            for(temp=0;temp<StudentList.size();temp++)
            {
                  student = (Student)StudentList.elementAt(temp);
                  if(student.SNo == SNo)
                  {
                        return student.Name;                        
                  }
            }
            return null;
      }


      public static void main(String args[])
      {
        Ass window = new Ass();

        window.setTitle("Assignment");
        window.pack();
        window.show();

      }


   
   




class SelStudent extends Frame implements ActionListener
{
    JLabel labelCaption;                  
    JList listStudents;
    JScrollPane sp_listStudents;
    JButton buttonOK;
    JButton buttonCancel;

    public SelStudent() {
        SelStudentLayout customLayout = new SelStudentLayout();

        setFont(new Font("Helvetica", Font.PLAIN, 12));
        setLayout(customLayout);

        labelCaption = new JLabel("Select a student");
        add(labelCaption);

        DefaultListModel listModel_listStudents = new DefaultListModel();
        listStudents = new JList(listModel_listStudents);
        sp_listStudents = new JScrollPane(listStudents);
        add(sp_listStudents);

        buttonOK = new JButton("OK");
        buttonOK.setActionCommand("OK");      
        buttonOK.addActionListener(this);
        add(buttonOK);

        buttonCancel = new JButton("Cancel");
        buttonCancel.setActionCommand("Cancel");      
        buttonCancel.addActionListener(this);
        add(buttonCancel);

        setSize(getPreferredSize());

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });




       enum = StudentList.elements();
       while(enum.hasMoreElements())
       {
            student = (Student)(enum.nextElement());
            listModel_listStudents.addElement(student.Name);            
       }


    }



    public void actionPerformed(ActionEvent e)
    {
                if ("OK".equals(e.getActionCommand()))
            {
                  //Generate the Issue DVD task
                  LibTask = new LibraryTask();
                  LibTask.TaskID = true;
                  dvd = (DVD)DVDList.elementAt(listDVD.getSelectedIndex());
                  LibTask.DVDSerialNo = dvd.SerialNo;
                  student = (Student)StudentList.elementAt(listStudents.getSelectedIndex());
                  LibTask.StudentID = student.SNo;
                  LibraryTasksList.addElement(LibTask);
                  hide();            
                }
            else
            {
                  hide();
            }
    }


};



}





class DVD
{
      int SerialNo;            //Serial No of DVD
      String Name;            //Name of Student
      int StudentNo;            //If DVD is issued to any student then this variable contains the Student No to whom it has been issed.      0 = DVD is available and is not issued       NON 0 Value = DVD is issued to a student
}



class Student
{
     int SNo;            //Student No
     String Name;            //Student Name
}



class LibraryTask
{
      boolean TaskID;
      int DVDSerialNo;
      int StudentID;
}



class BorrowThread implements Runnable
{
      Thread thread;
      Ass mainApp;
      LibraryTask LibTask;
      Random RndNum;

      public BorrowThread(Ass s)
      {
            thread = new Thread(this);
            thread.start();
            mainApp = s;

            RndNum = new Random( System.currentTimeMillis() );
      }


      public void run()
      {
            int temp;
            DVD dvd;

            while(true)
            {
                  LibTask = mainApp.getDVDIssueTask();
                  if(LibTask != null)
                  {
                              dvd = mainApp.getDVD(LibTask.DVDSerialNo, 1);
                              dvd.StudentNo = LibTask.StudentID;
                              mainApp.refreshList(1);
                              mainApp.addDVD(dvd, 2);
                              mainApp.refreshList(2);
                              mainApp.addHistory("DVD    " + dvd.Name + "    has been issued to    " + mainApp.getStudentName(LibTask.StudentID));
                  }
                  try
                  {
                        thread.sleep(RndNum.nextInt(150) + RndNum.nextInt(15));
                  }catch(Exception e){}
            }
      }
}






class ReturnThread implements Runnable
{
      Thread thread;
      Ass mainApp;
      LibraryTask LibTask;

      Random RndNum;
      
      public ReturnThread(Ass s)
      {
            thread = new Thread(this);
            thread.start();
            mainApp = s;

            RndNum = new Random( System.currentTimeMillis() );
      }


      public void run()
      {


            DVD dvd;

            while(true)
            {
                  LibTask = mainApp.getDVDReturnTask();
                  if(LibTask != null)
                  {
                        dvd = mainApp.getDVD(LibTask.DVDSerialNo, 2);
                        mainApp.refreshList(2);
                        mainApp.addDVD(dvd, 1);
                        mainApp.refreshList(1);
                        mainApp.addHistory(mainApp.getStudentName(dvd.StudentNo) + "    has return the DVD     " + dvd.Name);
                  }
                  try
                  {
                        thread.sleep(RndNum.nextInt(150) + RndNum.nextInt(15));
                  }catch(Exception e){}
            }

      }

}







class SelStudentLayout implements LayoutManager {

    public SelStudentLayout() {
    }

    public void addLayoutComponent(String name, Component comp) {
    }

    public void removeLayoutComponent(Component comp) {
    }

    public Dimension preferredLayoutSize(Container parent) {
        Dimension dim = new Dimension(0, 0);

        Insets insets = parent.getInsets();
        dim.width = 206 + insets.left + insets.right;
        dim.height = 243 + insets.top + insets.bottom;

        return dim;
    }

    public Dimension minimumLayoutSize(Container parent) {
        Dimension dim = new Dimension(0, 0);
        return dim;
    }
    public void layoutContainer(Container parent) {
        Insets insets = parent.getInsets();

        Component c;
        c = parent.getComponent(0);
        if (c.isVisible()) {c.setBounds(insets.left+16,insets.top+8,176,24);}
        c = parent.getComponent(1);
        if (c.isVisible()) {c.setBounds(insets.left+16,insets.top+32,176,168);}
        c = parent.getComponent(2);
        if (c.isVisible()) {c.setBounds(insets.left+16,insets.top+208,80,24);}
        c = parent.getComponent(3);
        if (c.isVisible()) {c.setBounds(insets.left+104,insets.top+208,88,24);}
    }
}







class GUIFileLayout implements LayoutManager
{

    public GUIFileLayout() {
    }

    public void addLayoutComponent(String name, Component comp) {
    }

    public void removeLayoutComponent(Component comp) {
    }

    public Dimension preferredLayoutSize(Container parent) {
        Dimension dim = new Dimension(0, 0);

        Insets insets = parent.getInsets();
        dim.width = 480 + insets.left + insets.right;
        dim.height = 362 + insets.top + insets.bottom;

        return dim;
    }

    public Dimension minimumLayoutSize(Container parent) {
        Dimension dim = new Dimension(0, 0);
        return dim;
    }

    public void layoutContainer(Container parent) {
        Insets insets = parent.getInsets();

        Component c;
        c = parent.getComponent(0);
        if (c.isVisible()) {c.setBounds(insets.left+16,insets.top+240,136,32);}
        c = parent.getComponent(1);
        if (c.isVisible()) {c.setBounds(insets.left+16,insets.top+64,136,168);}
        c = parent.getComponent(2);
        if (c.isVisible()) {c.setBounds(insets.left+16,insets.top+8,136,24);}
        c = parent.getComponent(3);
        if (c.isVisible()) {c.setBounds(insets.left+336,insets.top+64,136,168);}
        c = parent.getComponent(4);
        if (c.isVisible()) {c.setBounds(insets.left+176,insets.top+64,136,168);}
        c = parent.getComponent(5);
        if (c.isVisible()) {c.setBounds(insets.left+176,insets.top+240,136,32);}
        c = parent.getComponent(6);
        if (c.isVisible()) {c.setBounds(insets.left+16,insets.top+280,456,72);}
        c = parent.getComponent(7);
        if (c.isVisible()) {c.setBounds(insets.left+176,insets.top+8,136,24);}
        c = parent.getComponent(8);
        if (c.isVisible()) {c.setBounds(insets.left+336,insets.top+8,136,24);}
        c = parent.getComponent(9);
        if (c.isVisible()) {c.setBounds(insets.left+16,insets.top+40,136,24);}
        c = parent.getComponent(10);
        if (c.isVisible()) {c.setBounds(insets.left+176,insets.top+40,136,24);}
        c = parent.getComponent(11);
        if (c.isVisible()) {c.setBounds(insets.left+336,insets.top+40,136,24);}
    }
}


0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 35

Expert Comment

by:TimYates
ID: 9747963
This seems to work:

Notice the wait() in the two threads, and the notify() when there is data available for them

Tim

----------------------------

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;



public class Ass  extends Frame implements ActionListener
{
    //JOptionPane.showMessageDialog(this, "Message", "Title", JOptionPane.INFORMATION_MESSAGE);

    JButton buttonBorrow;
    JList listDVD;
    JScrollPane sp_listDVD;
    JLabel labelDVD;
    JList listWaiting;
    JScrollPane sp_listWaiting;
    JList listBorrow;
    JScrollPane sp_listBorrow;
    JButton buttonReturn;
    JList listHistory;
    JScrollPane sp_listHistory;
    JLabel labelBorrow;
    JLabel labelWaiting;
    JLabel labelDVD2;
    JLabel labelBorrow2;
    JLabel labelWaiting2;

    DefaultListModel listModel_listDVD;
    DefaultListModel listModel_listWaiting;
    DefaultListModel listModel_listBorrow;
    DefaultListModel listModel_listHistory;





    Student student;               //A object of Student
    DVD dvd;                    //A object of DVD

    Vector DVDList;               //This will be a collection of DVD's available in library.
                                  //This is collection of Student object

    Vector BorrowedDVDList;

    public Vector StudentList;     //This is a list of students. This is a collection of DVD
                              //object

    Vector  WaitingList;          //This a waiting student list. A new student waiting
                              //student waiting for a DVD will be added at the end of
                              //the collection. When a DVD is available then preference
                              //will be given to a student at the top of this list. This
                              //is a collection of Student Object

    Enumeration enum;               //This enumeration will be used to loop through the above Vector objects collection.


    LibraryTask LibTask;               //A single library task object
    Vector LibraryTasksList;          //When a DVD is issued to a student, that task is added to this
                              //collection. similarly when a DVD is return by a student, that task is
                              //is also added to this collection. Both IssueThread and ReturnThread monitor this
                              //collection, remove their relavent tasks from collection and then perform them.
                              //This is a collection of LibraryTask objects


    JDialog dialog;

    SelStudent selectStudentWindow;      //This select student window


    BorrowThread borrowThread;
    ReturnThread returnThread;



    public Ass()
    {
        GUIFileLayout customLayout = new GUIFileLayout();




        setFont(new Font("Helvetica", Font.PLAIN, 12));
        setLayout(customLayout);



        buttonBorrow = new JButton("Borrow");
       buttonBorrow.setActionCommand("Borrow");
       buttonBorrow.addActionListener(this);
        add(buttonBorrow);



       listModel_listDVD  = new DefaultListModel();
       listModel_listWaiting  = new DefaultListModel();
       listModel_listBorrow  = new DefaultListModel();
       listModel_listHistory = new DefaultListModel();


        listDVD = new JList(listModel_listDVD);
        sp_listDVD = new JScrollPane(listDVD);
        add(sp_listDVD);

        labelDVD = new JLabel("Available DVD's");
        add(labelDVD);

        listWaiting = new JList(listModel_listWaiting);
        sp_listWaiting = new JScrollPane(listWaiting);
        add(sp_listWaiting);

        listBorrow = new JList(listModel_listBorrow);
        sp_listBorrow = new JScrollPane(listBorrow);
        add(sp_listBorrow);

        buttonReturn = new JButton("Return");
       buttonReturn.setActionCommand("Return");
       buttonReturn.addActionListener(this);
        add(buttonReturn);

        listHistory = new JList(listModel_listHistory);
        sp_listHistory = new JScrollPane(listHistory);
        add(sp_listHistory);

        labelBorrow = new JLabel("Borrow DVD");
        add(labelBorrow);

        labelWaiting = new JLabel("Waiting List");
        add(labelWaiting);

        labelDVD2 = new JLabel("label_1");
        add(labelDVD2);

        labelBorrow2 = new JLabel("label_2");
        add(labelBorrow2);

        labelWaiting2 = new JLabel("label_3");
        add(labelWaiting2);

        setSize(getPreferredSize());

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });



        DVDList = new Vector();
       BorrowedDVDList = new Vector();
        StudentList = new Vector();
        WaitingList = new Vector();
       LibraryTasksList = new Vector();



       dvd = new DVD();
       dvd.SerialNo = 1;                    //Serial No of DVD
       dvd.Name = "National Geographics";     //name of DVD;
       dvd.StudentNo = 0;                    //DVD is not yet issued to any student so StudentNo will be 0
       DVDList.addElement(dvd);

       dvd = new DVD();
       dvd.SerialNo = 2;                    //Serial No of DVD
       dvd.Name = "Atlantic Dive";               //name of DVD;
       dvd.StudentNo = 0;                    //DVD is not yet issued to any student so StudentNo will be 0
       DVDList.addElement(dvd);

       dvd = new DVD();
       dvd.SerialNo = 3;                    //Serial No of DVD
       dvd.Name = "Africa Direct";               //name of DVD;
       dvd.StudentNo = 0;                    //DVD is not yet issued to any student so StudentNo will be 0
       DVDList.addElement(dvd);

       dvd = new DVD();
       dvd.SerialNo = 4;                    //Serial No of DVD
       dvd.Name = "Singapore Roars";          //name of DVD;
       dvd.StudentNo = 0;                    //DVD is not yet issued to any student so StudentNo will be 0
       DVDList.addElement(dvd);


      enum = DVDList.elements();
      while(enum.hasMoreElements())
      {
          dvd = (DVD)(enum.nextElement());
          listModel_listDVD.addElement(dvd.Name);
      }


     student = new Student();
     student.SNo = 1;
     student.Name = "Andy Aiken";
     StudentList.addElement(student);

     student = new Student();
     student.SNo = 2;
     student.Name = "Allan Bruce";
     StudentList.addElement(student);

     student = new Student();
     student.SNo = 3;
     student.Name = "Gordon Christie";
     StudentList.addElement(student);

     student = new Student();
     student.SNo = 4;
     student.Name = "Gary Ewing";
     StudentList.addElement(student);

     student = new Student();
     student.SNo = 5;
     student.Name = "David Fowler";
     StudentList.addElement(student);

     student = new Student();
     student.SNo = 6;
     student.Name = "Qiang Huo";
     StudentList.addElement(student);

     student = new Student();
     student.SNo = 7;
     student.Name = "Adil Hameed";
     StudentList.addElement(student);


     student = new Student();
     student.SNo = 8;
     student.Name = "Qiang Huo";
     StudentList.addElement(student);


     student = new Student();
     student.SNo = 9;
     student.Name = "Honghai Liu";
     StudentList.addElement(student);


     student = new Student();
     student.SNo = 10;
     student.Name = "Ying Liu";
     StudentList.addElement(student);


     student = new Student();
     student.SNo = 11;
     student.Name = "Mairi McCallum";
     StudentList.addElement(student);


     selectStudentWindow = new SelStudent();
     borrowThread = new BorrowThread(this);
     returnThread = new ReturnThread(this);
    }


    public void actionPerformed(ActionEvent e)
    {
              if ("Borrow".equals(e.getActionCommand()))
          {
               if(listDVD.getSelectedIndex() == -1)
                    JOptionPane.showMessageDialog(this, "Please select a DVD to Issue", "Select DVD", JOptionPane.INFORMATION_MESSAGE);
               else
               {
                   selectStudentWindow .setTitle("Issue DVD");
                    selectStudentWindow .pack();
                   selectStudentWindow.show();
               }
              }
          else
          {
               if(listBorrow.getSelectedIndex() == -1)
                    JOptionPane.showMessageDialog(this, "Please select a DVD to return", "Select DVD", JOptionPane.INFORMATION_MESSAGE);
               else
               {
                    //Generate the Return DVD task
                    LibTask = new LibraryTask();
                    LibTask.TaskID = false;
                    dvd = (DVD)BorrowedDVDList.elementAt(listBorrow.getSelectedIndex());
                    LibTask.DVDSerialNo = dvd.SerialNo;
                    LibraryTasksList.addElement(LibTask);
                    synchronized( returnThread )
                    {
                      returnThread.notify();
                    }
               }
           }
    }



    public synchronized LibraryTask getDVDIssueTask()
    {
       int temp;

       for(temp=0;temp<LibraryTasksList.size();temp++)
       {
          LibTask = (LibraryTask)LibraryTasksList.elementAt(temp);
          if(LibTask.TaskID == true)
          {
               LibraryTasksList.removeElementAt(temp);
               return LibTask;
          }
        }
     return null;
    }




    public synchronized LibraryTask getDVDReturnTask()
    {
       int temp;

       for(temp=0;temp<LibraryTasksList.size();temp++)
       {
          LibTask = (LibraryTask)LibraryTasksList.elementAt(temp);
          if(LibTask.TaskID == false)
          {
               LibraryTasksList.removeElementAt(temp);
               return LibTask;
          }
        }
     return null;
    }


     public synchronized void addHistory(String s)
     {
          listModel_listHistory.addElement(s);
     }



     public synchronized DVD getDVD(int SNO, int ListID)
     {
          int temp;

          if(ListID == 1)
          {
               for(temp=0;temp<DVDList.size();temp++)
               {
                    dvd = (DVD)DVDList.elementAt(temp);
                    if(dvd.SerialNo == SNO)
                    {
                         DVDList.removeElementAt(temp);
                         return dvd;
                    }
               }
          }
          else if(ListID == 2)
          {
               for(temp=0;temp<BorrowedDVDList.size();temp++)
               {
                    dvd = (DVD)BorrowedDVDList.elementAt(temp);
                    if(dvd.SerialNo == SNO)
                    {
                         BorrowedDVDList.removeElementAt(temp);
                         return dvd;
                    }
               }
          }
          return null;
     }



     public synchronized void addDVD(DVD dvd, int ListID)
     {
          if(ListID == 1)
               DVDList.insertElementAt(dvd, 0);
          else if(ListID == 2)
               BorrowedDVDList.insertElementAt(dvd, 0);
     }





     public synchronized void refreshList(int ListID)
     {
          if(ListID == 1)
          {
               while(listModel_listDVD.size() > 0)
                    listModel_listDVD.removeElementAt(0);

                enum = DVDList.elements();
                while(enum.hasMoreElements())
                {
                    dvd = (DVD)(enum.nextElement());
                    listModel_listDVD.addElement(dvd.Name);
                }
          }
          else if(ListID == 2)
          {
               while(listModel_listBorrow.size() > 0)
                    listModel_listBorrow.removeElementAt(0);


                enum = BorrowedDVDList.elements();
                while(enum.hasMoreElements())
                {
                    dvd = (DVD)(enum.nextElement());
                    listModel_listBorrow.addElement(dvd.Name);
                }
          }
          else if(ListID == 3)
          {


          }
     }



     public synchronized String getStudentName(int SNo)
     {
          Student student;
          int temp;
          for(temp=0;temp<StudentList.size();temp++)
          {
               student = (Student)StudentList.elementAt(temp);
               if(student.SNo == SNo)
               {
                    return student.Name;
               }
          }
          return null;
     }


     public static void main(String args[])
      {
        Ass window = new Ass();

        window.setTitle("Assignment");
        window.pack();
        window.show();

      }








class SelStudent extends Frame implements ActionListener
{
    JLabel labelCaption;
    JList listStudents;
    JScrollPane sp_listStudents;
    JButton buttonOK;
    JButton buttonCancel;

    public SelStudent() {
        SelStudentLayout customLayout = new SelStudentLayout();

        setFont(new Font("Helvetica", Font.PLAIN, 12));
        setLayout(customLayout);

        labelCaption = new JLabel("Select a student");
        add(labelCaption);

        DefaultListModel listModel_listStudents = new DefaultListModel();
        listStudents = new JList(listModel_listStudents);
        sp_listStudents = new JScrollPane(listStudents);
        add(sp_listStudents);

        buttonOK = new JButton("OK");
       buttonOK.setActionCommand("OK");
       buttonOK.addActionListener(this);
        add(buttonOK);

        buttonCancel = new JButton("Cancel");
       buttonCancel.setActionCommand("Cancel");
       buttonCancel.addActionListener(this);
        add(buttonCancel);

        setSize(getPreferredSize());

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });




      enum = StudentList.elements();
      while(enum.hasMoreElements())
      {
          student = (Student)(enum.nextElement());
          listModel_listStudents.addElement(student.Name);
      }


    }



    public void actionPerformed(ActionEvent e)
    {
              if ("OK".equals(e.getActionCommand()))
          {
               //Generate the Issue DVD task
               LibTask = new LibraryTask();
               LibTask.TaskID = true;
               dvd = (DVD)DVDList.elementAt(listDVD.getSelectedIndex());
               LibTask.DVDSerialNo = dvd.SerialNo;
               student = (Student)StudentList.elementAt(listStudents.getSelectedIndex());
               LibTask.StudentID = student.SNo;
               LibraryTasksList.addElement(LibTask);
               synchronized( borrowThread )
               {
                 borrowThread.notify() ;
               }
               hide();
              }
          else
          {
               hide();
           }
    }


};



}





class DVD
{
     int SerialNo;          //Serial No of DVD
     String Name;          //Name of Student
     int StudentNo;          //If DVD is issued to any student then this variable contains the Student No to whom it has been issed.      0 = DVD is available and is not issued       NON 0 Value = DVD is issued to a student
}



class Student
{
     int SNo;          //Student No
     String Name;          //Student Name
}



class LibraryTask
{
     boolean TaskID;
     int DVDSerialNo;
     int StudentID;
}

class BorrowThread implements Runnable
{
     Thread thread;
     Ass mainApp;
     LibraryTask LibTask;
     Random RndNum;

     public BorrowThread(Ass s)
     {
           thread = new Thread(this);
          thread.start();
          mainApp = s;

          RndNum = new Random( System.currentTimeMillis() );
     }


     public void run()
     {
          int temp;
          DVD dvd;

          try
          {
            while( true )
            {
              synchronized( this )
              {
                wait() ;
                LibTask = mainApp.getDVDIssueTask() ;
                if( LibTask != null )
                {
                  dvd = mainApp.getDVD( LibTask.DVDSerialNo, 1 ) ;
                  dvd.StudentNo = LibTask.StudentID ;
                  mainApp.refreshList( 1 ) ;
                  mainApp.addDVD( dvd, 2 ) ;
                  mainApp.refreshList( 2 ) ;
                  mainApp.addHistory( "DVD    " + dvd.Name +
                                      "    has been issued to    " +
                                      mainApp.getStudentName( LibTask.StudentID ) ) ;
                }
              }
            }
          }
          catch( InterruptedException ex )
          {
            ex.printStackTrace();
          }
     }
}

class ReturnThread implements Runnable
{
     Thread thread;
     Ass mainApp;
     LibraryTask LibTask;

     Random RndNum;

     public ReturnThread(Ass s)
     {
           thread = new Thread(this);
          thread.start();
          mainApp = s;

          RndNum = new Random( System.currentTimeMillis() );
     }


     public void run()
     {


          DVD dvd;

          try
          {
            while( true )
            {
              synchronized( this )
              {
                wait() ;
                LibTask = mainApp.getDVDReturnTask() ;
                if( LibTask != null )
                {
                  dvd = mainApp.getDVD( LibTask.DVDSerialNo, 2 ) ;
                  mainApp.refreshList( 2 ) ;
                  mainApp.addDVD( dvd, 1 ) ;
                  mainApp.refreshList( 1 ) ;
                  mainApp.addHistory( mainApp.getStudentName( dvd.StudentNo ) +
                                      "    has return the DVD     " + dvd.Name ) ;
                }
              }
            }
          }
          catch( InterruptedException ex )
          {
            ex.printStackTrace();
          }

     }

}

class SelStudentLayout implements LayoutManager {

    public SelStudentLayout() {
    }

    public void addLayoutComponent(String name, Component comp) {
    }

    public void removeLayoutComponent(Component comp) {
    }

    public Dimension preferredLayoutSize(Container parent) {
        Dimension dim = new Dimension(0, 0);

        Insets insets = parent.getInsets();
        dim.width = 206 + insets.left + insets.right;
        dim.height = 243 + insets.top + insets.bottom;

        return dim;
    }

    public Dimension minimumLayoutSize(Container parent) {
        Dimension dim = new Dimension(0, 0);
        return dim;
    }
    public void layoutContainer(Container parent) {
        Insets insets = parent.getInsets();

        Component c;
        c = parent.getComponent(0);
        if (c.isVisible()) {c.setBounds(insets.left+16,insets.top+8,176,24);}
        c = parent.getComponent(1);
        if (c.isVisible()) {c.setBounds(insets.left+16,insets.top+32,176,168);}
        c = parent.getComponent(2);
        if (c.isVisible()) {c.setBounds(insets.left+16,insets.top+208,80,24);}
        c = parent.getComponent(3);
        if (c.isVisible()) {c.setBounds(insets.left+104,insets.top+208,88,24);}
    }
}

class GUIFileLayout implements LayoutManager
{

    public GUIFileLayout() {
    }

    public void addLayoutComponent(String name, Component comp) {
    }

    public void removeLayoutComponent(Component comp) {
    }

    public Dimension preferredLayoutSize(Container parent) {
        Dimension dim = new Dimension(0, 0);

        Insets insets = parent.getInsets();
        dim.width = 480 + insets.left + insets.right;
        dim.height = 362 + insets.top + insets.bottom;

        return dim;
    }

    public Dimension minimumLayoutSize(Container parent) {
        Dimension dim = new Dimension(0, 0);
        return dim;
    }

    public void layoutContainer(Container parent) {
        Insets insets = parent.getInsets();

        Component c;
        c = parent.getComponent(0);
        if (c.isVisible()) {c.setBounds(insets.left+16,insets.top+240,136,32);}
        c = parent.getComponent(1);
        if (c.isVisible()) {c.setBounds(insets.left+16,insets.top+64,136,168);}
        c = parent.getComponent(2);
        if (c.isVisible()) {c.setBounds(insets.left+16,insets.top+8,136,24);}
        c = parent.getComponent(3);
        if (c.isVisible()) {c.setBounds(insets.left+336,insets.top+64,136,168);}
        c = parent.getComponent(4);
        if (c.isVisible()) {c.setBounds(insets.left+176,insets.top+64,136,168);}
        c = parent.getComponent(5);
        if (c.isVisible()) {c.setBounds(insets.left+176,insets.top+240,136,32);}
        c = parent.getComponent(6);
        if (c.isVisible()) {c.setBounds(insets.left+16,insets.top+280,456,72);}
        c = parent.getComponent(7);
        if (c.isVisible()) {c.setBounds(insets.left+176,insets.top+8,136,24);}
        c = parent.getComponent(8);
        if (c.isVisible()) {c.setBounds(insets.left+336,insets.top+8,136,24);}
        c = parent.getComponent(9);
        if (c.isVisible()) {c.setBounds(insets.left+16,insets.top+40,136,24);}
        c = parent.getComponent(10);
        if (c.isVisible()) {c.setBounds(insets.left+176,insets.top+40,136,24);}
        c = parent.getComponent(11);
        if (c.isVisible()) {c.setBounds(insets.left+336,insets.top+40,136,24);}
    }
}
0
 
LVL 7

Expert Comment

by:grim_toaster
ID: 9748032
But wouldn't you be wanting to synchronize on the same object, as opposed to this (just in cae there are more than one return threads?  And if you get an InterruptedException, you'll exit the loop!
0
 
LVL 35

Expert Comment

by:TimYates
ID: 9748067
> But wouldn't you be wanting to synchronize on the same object, as opposed to this

Maybe

> (just in cae there are more than one return threads?

Why would there be?  If there are, then this is a bug surely?

> And if you get an InterruptedException, you'll exit the loop!

Yeah...it got interrupted...  I guess I prefer my Threads to die when I interrupt them :-)

Evil Tim
0
 
LVL 35

Expert Comment

by:TimYates
ID: 9748070
;-)
0
 
LVL 7

Expert Comment

by:grim_toaster
ID: 9748271
Well letting them die is better than while(true) anyway!  Should really be while(booleanValue), which can be set to false at some point.
But we won't get into that now!

One other point though!  The code is very linear, you should try to seperate out large duplicate calls, for example your DVD class, consider creating another constructor that takes the serialNo and name as arguments, so that when you construct it you can create and add to the vector in one line (as opposed to several).

Also, I would suggest synchronizing on the Vector involved, as opposed to your Frame instance, it may be slightly tougher to write correctly but doing so would allow people to do different things at the same time (for example, would you want to stop someone checking out a DVD, just because someone else is doing a query on a user name?).
0
 
LVL 92

Expert Comment

by:objects
ID: 9751456
> Both threads can access shared data. maipulate it and also refreshes the GUI of main program.

Swing is single threaded and not thread safe.
Your gui should only be access by the EDT and not any other thread.

This also implies there is no point synchonising any method that access your gui (or it's model), all it will do is slow things down.

Use EventQueue.invokeLater() and invokeAndWait() to execute code on the EDT.
0
 
LVL 1

Author Comment

by:shahzad73
ID: 9753154
hey i have removed all the Synchronized key words before all methods called by my threads. Aslo i take all of my code from ReturnThread and IssueThread in a single Thread which looks for any tasks from main program and handle it whether it is Issue or Return DVD task. And now it seems to be working fine


Tim you suggestion is good one. i will also try with that. But grim_toaster was right. there can be more than one Issue and ReturnDVD threads working. i think it was supposed to work. any suggestion how to make it correct so it works this way.


Shahzad
0
 
LVL 1

Author Comment

by:shahzad73
ID: 9754067

hello

i think i got the problem. I am calling different methods of the main program. Some of these methods refresh the GUI. means refresh the contents of the List and so on. I think refreshing the GUI from the threads is causing problem. means when i did the program with out threads .. it works fine  .. not in the thread.

Now another problem ... how GUI will refresh itself. If i create another thread which refreshes the GUI it will definately halt the program. So i have to refresh the GUI outside threads.

How will i do this. if i call a method which continuously refreshes the GUI from main .. . it says you can not access INstance objects from the static main.

Any suggestion how GUI refresh it self when a thread changes the GUI contents.


Shahzad
0
 
LVL 92

Accepted Solution

by:
objects earned 500 total points
ID: 9756503
> I think refreshing the GUI from the threads is causing problem.

That's what I said earlier :)

> Any suggestion how GUI refresh it self when a thread changes the GUI contents.

See my earlier comment.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now