Using Thread.sleep()

When I put Thread.sleep() in my code, the debugger says I need to catch it. How do I do that?

But in general, you don't want to just smother exceptions like that. It's okay when you're sleeping (or can be) because often if you're interrupted, you want to just ignore it and move on. However, there's more to handling exceptions than just an empty catch block.
http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html

Similar Messages

  • Work manager using thread.sleep or delay doesn't work

    Hi all,
    I used Spring framework and oracle weblogic 10.3 as a container.
    I used workmanager for manage my thread, I already made one thread that managed by workmanager. Fortunately spring provide the delegation class for using workmanager, so I just need to put it on applicationContext.xml.
    But when I put the "while" and TimeUnit for sleep the process on desired delayed time, the deployment process never finished. It seems the deployment process never jump out from while loop for finishing the deployment.
    Why?, As I know using typical thread, there is no issue like this. Should I use another strategy for make it always loop and delay.
    This is my simple code :
    import java.util.concurrent.TimeUnit;
    import org.springframework.core.task.TaskExecutor;
    public class TaskExecutorSample{
         Boolean shutdown = Boolean.FALSE;
         int delay = 8000;
         TimeUnit unit = TimeUnit.SECONDS;
         private class MessageGenerator implements Runnable {
              private String message;
              public MessageGenerator(String message){
                   this.message = message;
              @Override
              public void run() {
                   System.out.println(message);
         private TaskExecutor taskExecutor;
         public TaskExecutorSample(TaskExecutor taskExecutor){
              this.taskExecutor = taskExecutor;
              try {
                   while (shutdown.equals(Boolean.FALSE)){
                        this.printMessage();
                        unit.sleep(delay);
              } catch (Exception e) {
                   System.out.println(e.getMessage());
         public void printMessage() {
              taskExecutor.execute(new MessageGenerator("Print this Messages"));
    Really thanks in advance.
    Regards,
    Kahlil
    Edited by: Kahlil on May 26, 2010 2:38 PM
    Edited by: Kahlil on May 26, 2010 2:42 PM

    Hi,
    i m not sure whether it's an issue with Spring or not. But i tried using Thread.sleep(1000) in a Simple webapplication to see Workmanagers works properly or not. I found that it works extremely great: http://weblogic-wonders.com/weblogic/2010/01/24/workmanager-at-webapplication-level/
    Thanks
    Jay SenSharma

  • Confusion using Thread.sleep() method

    I tried it in this program
    class NewThread implements Runnable {
      String name; // name of thread
      Thread t;
      NewThread(String threadname) {
        name = threadname;
        t = new Thread(this, name);
        System.out.println("New thread: " + t);
        t.start(); // Start the thread
      // This is the entry point for thread.
      public void run() {
        try {
          for(int i = 5; i > 0; i--) {
            System.out.println(name + ": " + i);
            Thread.sleep(1000);
        } catch (InterruptedException e) {
          System.out.println(name + "Interrupted");
        System.out.println(name + " exiting.");
    class MultiThreadDemo {
      public static void main(String args[]) {
        new NewThread("One"); // start threads
        new NewThread("Two");
        new NewThread("Three");
        try {
          // wait for other threads to end
          Thread.sleep(10000);
        } catch (InterruptedException e) {
          System.out.println("Main thread Interrupted");
        System.out.println("Main thread exiting.");
    }the output is
    one: 5
    two: 5
    three 5
    delay of 1 second
    one:4
    two: 4
    three: 4
    delay of 1second
    what all i know about sleep() is that it pause the currently executing thread for specified time. hence in above program when first thread runs and prints value 5 then it should get paused for 1 second cause there is Thread.sleep(1000) after println() statement.
    and output should be
    one: 5
    delay of 1 second
    two: 5
    delay of 1 second
    three: 5
    delay of 1 second
    but this is not actually happens. may be i am wrong about Thread.sleep method() or something else.
    would you guys please clear it?
    regards
    san

    Thread.sleep() only sleeps the current thread. As each thread runs concurrently they all print concurrently and all sleep concurrently.

  • How to use Thread.sleep() with Java Berkeley Base API?

    Hi,
    I have explained the weird problem about the server was too busy to response to SSH but it continued to finish to run (Server not response when inserting millions of records using Java Base API
    Even I tried to increase CachSize and renice Java program, but it did not work. So, I am thinking to set sleeping time for threads in Java Berkeley Base API (using “ps” command, there were 18 light weight processes created). My program did not implement transaction or concurrency because it simply creates (millions) databases records only. Is it possible and correct to do like this in the code:
    try{
    //do create a db record
    Thread.currentThread().sleep(1000);//sleep for 1000 ms
    catch(ItrerruptedException ie){
    Thank you for your kindly suggestion.
    Nattiya

    where can I get the help doc about use AT commands in java.
    Can you give me some code example about this. It is
    difficulty to me to write it myself.You simply have to send the characters and receive the characters via the comm extension. Here is the ITU standard command set - http://ridge.trideja.com/wireless/atcommands/v250.pdf. Various modems and other devices extend this in a number of ways, you may need to find documentation specific to your device as well. But start with the standard.

  • What's wrong to put Thread.sleep in a session bean?

    i am working on a trading platform and i think there is a design flaw. The part i am working on is the Order Management module. When an order value object is published to a JMS topic and picked up by a MDB. The MDB, in turn, calls a session bean (could be stateless, I didn't check), OrderEngineBean. After this bean saves the order vo into database and broadcast the message to all involved parties, it suspends for 12 sec, using Thread.sleep, so other parities might have a chance to update the vo. If no update occurs, the order is considered expired and abandoned.
    It looks awkward to me to use a Thread.sleep in a session, but I haven't come out with a better idea to deal with the scenario like above.
    Anyone can help me out?
    Thanks a lot!
    Sway

    Setting the property "max-beans-in-free-pool" is not the answer to this issue. By setting this property to 1, the container merely instantiates and keeps one instance of the bean in the free pool at the "start" of the app server. But if the container comes across more than one requests for the same EJB simultaneoulsy, then it will create new instances at that time to handle the requests simultaneously.
    You are seeing intermixed log messages between two threads because these messages are being logged from two different instances of the EJB and NOT the same instance of the EJB. The container does synchronizes the calls on "a method" on "a instance". So what you are seeing are the messages coming from "a method" on "two different instances" of the same EJB.
    You can refer to the EJB 2.0 specification section 6.11.6 Non-reentrant instances for details about simultaneous access to the same session object.

  • Java Thread.sleep() on Windows 8 stops in S3 sleep status

    There's a desktop application that uses Thread.sleep() to achieve long (minutes or hours) delays. This same application has been working fine from Windows XP through Windows 7. The application calculates how far in the future it needs to do something, then hits a Thread.sleep(msToWait). This has been working fine, even if the system happens to go into S3 or S4 sleep state during the wait.  All is good as long as the machine is awake at the time when the sleep expires.
    As of Windows  8 (and 10), though, the code after Thread.sleep() does not execute "on time" if the machine has been in S3 during the sleep interval. It appears that the machine begins executing code at "msToWait" plus the time the machine has been in S3.
    Earlier versions of Windows did not exhibit this behavior; code after Thread.sleep() waited the right amount of time, irrespective of sleep status.
    A test program and procedure were developed. The procedure is to 1) run the program, 2) cause the machine to sleep for about a minute, then 3) wake the machine and wait for the program to finish.
    If this the program is run on Windows 10 (reporting as 8) with JVM Version: 25.40-b25, it fails (the 63589 corresponds to the minute that the machine was in S3):
    C:\Users\Tester\Downloads>SleepTester.exe
    Wed Apr 01 10:47:35 PDT 2015 Using default number of minutes: 5
    Wed Apr 01 10:47:35 PDT 2015 You can use "SleepTester -minutes 10" to have it sleep for 10 minutes, for example.
    Wed Apr 01 10:47:35 PDT 2015 JVM Version: 25.40-b25 Windows Version: Windows 8
    Wed Apr 01 10:47:35 PDT 2015 The program will now wait for 5 minutes.  Expect wrap-up at Wed Apr 01 10:52:35 PDT 2015
    Wed Apr 01 10:53:38 PDT 2015 The system has come through the Thread.sleep(300000).
    Wed Apr 01 10:53:38 PDT 2015 This should be a low number: 63589
    Wed Apr 01 10:53:38 PDT 2015 This appears to be operating incorrectly...the expected sleep time has NOT been achieved.
    Wed Apr 01 10:53:38 PDT 2015 Program is ending.
    If the process is run on Windows 7, it does not fail:
    Wed Apr 01 17:12:18 EDT 2015 Java Runtime Version: 1.8.0_31-b13 JVM Version: 25.31-b07 Windows Version: Windows 7
    Wed Apr 01 17:12:18 EDT 2015 The program will now wait for 6 minutes.  Expect wrap-up at Wed Apr 01 17:18:18 EDT 2015
    Wed Apr 01 17:18:18 EDT 2015 The system has come through the Thread.sleep(360000).
    Wed Apr 01 17:18:18 EDT 2015 This should be a low number: 0
    Wed Apr 01 17:18:18 EDT 2015 Program is ending.
    This is the guts of  test program:
    [code]
    public static void main(String[] args) throws Exception {
       System.out.println(new Date() + " Java Runtime Version: " + System.getProperty("java.runtime.version") + " JVM Version: " + System.getProperty("java.vm.version") + " Windows Version: " + System.getProperty("os.name"));
       long msDelay = mMinutes * 60 * 1000;
       long wakePoint = new Date().getTime() + msDelay;
       System.out.println(new Date() + " The program will now wait for " + mMinutes + " minutes. Expect wrap-up at " + new Date(wakePoint));
       Thread.sleep(msDelay); // If the machine goes into S3 during this interval, it should not matter, as long as it's awake when it fires.
       System.out.println(new Date() + " The system has come through the Thread.sleep(" + msDelay + "). ");
       long msAccuracy = Math.abs(new Date().getTime() - wakePoint);
       System.out.println(new Date() + " This should be a low number: " + msAccuracy);
       if (msAccuracy > 1000) System.out.println(new Date() + " This appears to be operating incorrectly...the expected sleep time has NOT been achieved.");
       System.out.println(new Date() + " Program is ending.");
    [/code]
    Was the change in behavior from earlier versions of Windows intentional?  Is it something that the JVM is controlling, or is there a difference in the underlying OS that is beyond the control of the JVM?

    I might need to create a work-around whereby I maintain a watch of the msDelay and the system clock.  If there is a discontinuity (which would only happen on Windows 8 or higher), then I would repair the msDelay value.
    A separate (but related) question:
    Can I conclude that since older JVM's running on Windows 8 still have the problem, that it's a Windows issue, and not a JVM issue?

  • Alternative to Thread.Sleep in catch?

    Is there any other way to make the code wait than using Thread.Sleep in catch, because Thread.Sleep disturbs other objects on my form. Here is what I'm trying to do:
    Try{
    //do something
    catch
    // wait 10 seconds
    //retry

    Timers are a bit of a nuisance what with keeping your form in memory even when you try and dispose the things.
    You could push the thing you're doing onto another thread.
    Use async await.
    You could then use Task.Delay.
    A very simplified example:
    private async void Button_Click1(object sender, RoutedEventArgs e)
    await Task.Delay(2000);
    // Do something
    Because that's an async method processing returns to the caller when it hits the await.
    That then pauses 2 seconds without impinging on your UI thread.
    Before the separate thread continues with the code after your await.
    You could put your try catch into a method like that and it'd do what you want without a timer.
    10 seconds seems a bit of a short time by the way.
    Hope that helps.
    Recent Technet articles:
    Property List Editing ;  
    Dynamic XAML

  • Repaint() being delayed by Thread.sleep()

    Hello, I am programming a Memory-like card game, where the user picks cards and if they match they stay flipped over, but if they don't match the cards will be displayed for a second and then flipped back over. However, I am running into a problem when the cards do not match, the game will wait (using Thread.sleep()) and then flip the cards back over. The problem is that the second card picked, that is determined to not be a match, is not showing the face before the cards are returned to the hidden state. I think that it is being flipped twice in a row at the end of the sleep(), therefore never actually displaying the front of the card. I have tried putting repaint() everywhere, and there is one before the sleep(), but it still doesn't seem to work properly. Here is the code for my mouse clicked event. Thanks for any help!
      public void mouseClicked(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        Card temp = null;
        for (int i = 0; i < 52; i++) {
          temp = cards.getCard(i);
          if (temp.contains(x, y)) {
            if (temp.isFront() == true)
              return;
            temp.swapImg();
            this.repaint();
            if (flipped == null) {
              flipped = temp;
            } else {
              if (temp.getVal() == flipped.getVal()) {
                // we have a pair
              } else {
                // cards don't match.. start over
                try {
                  Thread.sleep(500);
                } catch (InterruptedException ie) {
                  System.out.println("Thread was interrupted!\r\n");
                temp.swapImg();
                flipped.swapImg();
              flipped = null;
            break;
      }

    Don't use Thread.sleep() inside a Listener. You are blocking the EDT which prevents the GUI from repainting itself.
    Use a Swing Timer to schedule the flipping of the cards.

  • Troubles using Thread & repainting components at same time.

    Hi. I have a frame which contains several labels. If i clicked on a label, it runs a method which changes label's aspect. Then, i need that once passed a second, label's aspect changes to original aspect. The problem is that controls dont repaint while i use Thread.sleep(1000) method. I have tried to call repaint() (both frame and label) before calling Thread.sleep() but it doesnt work too.
    Any idea on how to solve this problem? Thanks for answers :)

    Well, it wasnt a layout problem.
    I've found solution trough camickr's link. Now im using Timer and TimerTask classes and all is working fine.
    Thank you very much :)

  • Contiunous running programs: Thread.sleep vs. Scheduled Tasks

    Hello,
    I have simulation programs that should run continuously for weeks at a time. I am seeking any advice or comments on the best way to do something like this.
    Some programs run every 30 seconds; others run once per hour; others run once per day. These programs involve simulating the use of a popular website by reading web pages and inserting records into Oracle 9i databases.
    As far as the "every 30 seconds" program, I use Thread.sleep to pause the program for each interval. Is this a good method?
    What about programs running once per hour or per day? I have used the Windows XP Scheduled Task program to execute the program. Is this a good method?
    Does anybody know of a better way to do such things?
    Any comments or helpful links are greatly appreciated.
    Thank you,
    Logan

    I have simulation programs that should run
    continuously for weeks at a time. I am seeking any
    advice or comments on the best way to do something
    like this.If you have a simulator, does it have to simulate time on a one to one basis. Could it not simulate 30 seconds, every 3 seconds and thus not need to run for the full week. If you have to run in real time, what are you simulating.
    Some programs run every 30 seconds; others run once
    per hour; others run once per day. These programs
    involve simulating the use of a popular website by
    reading web pages and inserting records into Oracle
    9i databases.
    As far as the "every 30 seconds" program, I use
    Thread.sleep to pause the program for each interval.
    Is this a good method?No. Sleep for 30 seconds just means there is atleast 30 seconds delay from the end of the last task to the start of the next task. This could means every 30.1 seconds or even every 33 seconds depending on how long the task takes to run.
    If you create a single ScheduledExecutorService you can run a task with any period you suggest with a dynamic number of threads.
    e.g.
    Execuotrs.newScheduledThreadPool(1);
    >
    What about programs running once per hour or per day?See previous.
    I have used the Windows XP Scheduled Task program to
    execute the program. Is this a good method?If it is a couple of times per day or per week this is a good choice.
    >
    Does anybody know of a better way to do such things?see previous.

  • Servlets, Threads, sleep and wait

    Hi,
    I am new to servlet programming and have a problem.
    I want to create a servlet that is also Runnable. It should hold the HTTP request open, and then wait() or sleep(), waking up regularly to send data to the client.
    My code seems to work OK, and in the server logs I can see the debug messages where my servlet is sleeping and waking up. However, it doesn't keep the connection open. Instead, any clients that try to connect instantly receive an empty response.
    Can anyone explain why this is? I am a bit lost. Is the server (Tomcat) cutting my request off when I start to sleep or what?
    dave

    OK. Now seems like I have it working with sleep().
    I was doing something pretty dumb and assuming that a new HttpServlet instance was created for every request - doing things like this.request = request; - obviously this didn't work too wlell ;-)
    Now just using Thread.sleep() it works much better
    One more question - how can I get a separate servlet to call notify() on this servlet so that it wakes up and delivers its message? (I know I need to call wait() not sleep())
    Thanks
    dave

  • Using Thread.currentthread.sleep but not delaying appropriately

    Ok, here it goes. Im currently using the thread.sleep method to delay the changing of the text within some labels. I have 3 labels which represent some arrays. I then sort the arrays. Im trying to throw a delay in so that the user can see the changes happen to the array. Although, when I call the wait.millisec(1000) in (the sleep function I threw into its own wait class) it seems that the waiting all happens at the end. I dont see it during the loop to show the arrangement changes within the arrays. I stepped through the code using the debugger, but it doesnt seem to help.
    Look in the buttonListener within the FourX class.
    * SortTest.java                                   Author:Tim Dudek
       This trivial program tests the insertion sort and selection sort
       subroutines.  The data is then shown graphically.
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    public class SortTest {
       final static int ARRAY_SIZE = 10;  // Number of items in arrays to be sorted.
                                            // (This has to be 10 or more.)
       public static int[] A, B;
       public static JLabel lblOrig, lblSS, lblIS;
       public static void main(String[] args) {
            JFrame frame = new JFrame ("Tim Dudek");
              frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              FourX display = new FourX();//create the main panel
              frame.setSize(450, 320);
              frame.getContentPane().add(display);
              frame.setVisible(true);  
          A = new int[ARRAY_SIZE];     // Make an array  ints
          for (int i = 0; i < A.length; i++){      // Fill array A with random ints.
             A[i] = (int)(100*Math.random());
             lblOrig.setText(lblOrig.getText() + " "     + A);
    lblIS.setText(lblIS.getText() + " "     + A[i]);
    lblSS.setText(lblSS.getText() + " "     + A[i]);
    B = (int[])A.clone(); // make B an exact copy of A.
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    public class FourX extends JPanel {
         static final long serialVersionUID = 1L; //eclipse echo problem
         private JLabel lblO, lblI, lblS;
         private JButton sort;
         public FourX(){//JLabel lblOrig,JLabel lblSS, JLabel lblIS){
              setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
              SortTest.lblSS = new JLabel ("");
              SortTest.lblOrig = new JLabel ("");
              SortTest.lblIS = new JLabel ("");
              lblO = new JLabel("Orginal", JTextField.LEFT);
              lblI = new JLabel("Insertion Sort", JTextField.LEFT);
              lblS = new JLabel("Selection Sort", JTextField.LEFT);
              sort = new JButton("Sort");     
              sort.addActionListener(new buttonListener());
              SortTest.lblSS.setFont(new Font("Arial", Font.BOLD, 30));
              SortTest.lblSS.setHorizontalAlignment(JTextField.CENTER);
              SortTest.lblSS.setBorder(BorderFactory.createLineBorder (Color.RED, 3));
              SortTest.lblIS.setFont(new Font("Arial", Font.BOLD, 30));
              SortTest.lblIS.setHorizontalAlignment(JTextField.CENTER);
              SortTest.lblIS.setBorder(BorderFactory.createLineBorder (Color.BLUE, 3));
              SortTest.lblOrig.setFont(new Font("Arial", Font.BOLD, 30));
              SortTest.lblOrig.setHorizontalAlignment(JTextField.CENTER);
              SortTest.lblOrig.setBorder(BorderFactory.createLineBorder (Color.BLACK, 3));
              add(Box.createRigidArea(new Dimension (10, 10)));
              add(lblO);
              add(SortTest.lblOrig);
              add(Box.createRigidArea(new Dimension (10, 10)));
              add(lblS);
              add(SortTest.lblSS);
              add(Box.createRigidArea(new Dimension (10, 10)));
              add(lblI);
              add(SortTest.lblIS);
              add(Box.createRigidArea(new Dimension (10, 10)));
              add(sort);
         private class buttonListener implements ActionListener{
              public void actionPerformed (ActionEvent event){
              // sort A into increasing order, using selection sort
                   for (int lastPlace = SortTest.A.length-1; lastPlace > 0; lastPlace--) {
                        Wait.milliSec(50);
                   //Find the largest item among A[0], A[1], ... A[lastPlace],
              // and move it into position lastPlace by swapping it with
              // the number that is currently in position lastPlace
                        int maxLoc = 0; // location of largest item seen so far
                   for (int j = 1; j <= lastPlace; j++) {
                        if (SortTest.A[j] > SortTest.A[maxLoc])
                   maxLoc = j; // Now, location j contains the largest item seen
                   int temp = SortTest.A[maxLoc]; // swap largest item with A[lastPlace]
                   SortTest.A[maxLoc] = SortTest.A[lastPlace];
                   SortTest.A[lastPlace] = temp;
                   Wait.milliSec(100);//<------------ waiting???>
                   SortTest.lblSS.setText("");
                   for (int i = 0; i < SortTest.A.length; i++){
                        SortTest.lblSS.setText(SortTest.lblSS.getText() + " "     + SortTest.A[i]);
                   Wait.oneSec();//<------------ waiting???>
                   // sort the array A into increasing order
                   int itemsSorted; // number of items that have been sorted so far
                   for (itemsSorted = 1; itemsSorted < SortTest.B.length; itemsSorted++) {
                        // assume that items A[0], A[1], ... A[itemsSorted-1] have
                        // already been sorted, and insert A[itemsSorted] into the list.
                        int temp = SortTest.B[itemsSorted]; // the item to be inserted
                        int loc = itemsSorted - 1;
                        while (loc >= 0 && SortTest.B[loc] > temp) {
                             SortTest.B[loc + 1] = SortTest.B[loc];
                             loc = loc - 1;
                        SortTest.B[loc + 1] = temp;
                        Wait.milliSec(100);//<------------ waiting???>                    SortTest.lblIS.setText("");
                        for (int i = 0; i < SortTest.B.length; i++){
                             SortTest.lblIS.setText(SortTest.lblIS.getText() + " "     + SortTest.B[i]);
    public class Wait {
         public static void oneSec() {
              try {
                   Thread.currentThread().sleep(1000);
              catch (InterruptedException e) {
                   e.printStackTrace();
         public static void milliSec(long s) {
              try {
                   Thread.currentThread().sleep(s);
              catch (InterruptedException e) {
                   e.printStackTrace();

    Wow, ok. this is extrodinarily confusing. I read the tutorials, but they're not easy to follow.
    So, what I did was at the entry point:
    public class SortTest implements Runnable {
       final static int ARRAY_SIZE = 10;  // Number of items in arrays to be sorted.
                                            // (This has to be 10 or more.)
       public static int[] A, B;
       public static JLabel lblOrig, lblSS, lblIS;
       public static void main(String[] args) {
            (new Thread(new SortTest())).start();
       public void run(){
            JFrame frame = new JFrame ("Tim Dudek");
              frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              FourX display = new FourX();//create the main panel
              frame.setSize(450, 320);
              frame.getContentPane().add(display);
              frame.setVisible(true);  
          A = new int[ARRAY_SIZE];     // Make an array  ints
          for (int i = 0; i < A.length; i++){      // Fill array A with random ints.
             A[i] = (int)(100*Math.random());
             lblOrig.setText(lblOrig.getText() + " "     + A);
    lblIS.setText(lblIS.getText() + " "     + A[i]);
    lblSS.setText(lblSS.getText() + " "     + A[i]);
    B = (int[])A.clone(); // make B an exact copy of A.
    Ok, as I understand, this creates the initial thread to build the gui. Now you suggest that when the user hits "sort" that a second thread be created to handle the sorting routine.  From what I understand I can only inherit from one class in java.  My buttonListener already implements ActionListener. I obviously cant implement ActionListener and Runnable.  Do you have a suggestion? Maybe a link to an example?
    I'm pretty lost. 
    Tim                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Java Program Using Threads

    Hi there, im really new and have just started programming in Java, i have to create a java program which implement threads. Thread.Wait, thread.start them etc.
    Here is the problem, any guidance would be great cheers guys
    The manager of a company employs 3 secretaries who are of varying ability, but who all work extremely fast. Secretary A is the most experienced secretary and is capable of typing up a letter once every second. Secretary B is less experienced and is capable of typing up a letter once every 2 seconds. Secretary C is the junior secretary and is capable of typing up a letter once every 4 seconds. When a secretary has typed up a letter he leaves it in the manager?s tray for him to remove and sign. The manager removes and signs a letter from the tray once every 2 seconds. The tray can hold a maximum of 5 letters at a time. The tray?s limited capacity sometimes causes the various workers to be delayed. For example, if the tray is full after a letter has been typed, the secretaries must wait until the manager makes a space available before they can add another letter to the tray. Similarly, the manager must wait for at least one letter to appear in the tray before he can take it out and sign it.
    In your program, make use of threads to represent each of the workers (the 3 secretaries and the manager), so that they can work in parallel. You will also need to declare a tray object, and ensure that all communication is properly synchronised to avoid indeterminacy and deadlock. While an office worker is busy typing a letter or signing it, you should send that thread to sleep for the appropriate time period. This can be achieved with a call to:
    Thread.sleep(m);
    where m is the number of milliseconds for which the thread should suspend.
    The output from your program should take the form of a running commentary on the activity taking place in the office. An extract from it might look something like this (though it is up to you how you word this):
    Secretary A is ready to type a letter
    Secretary A has typed a letter, number now typed = 6
    Tray full. Secretary must wait until a letter has been removed before adding another
    Secretary C has typed a letter, number now typed = 2
    Tray full. Secretary must wait until a letter has been removed before adding another
    A letter has been removed from the tray. Tray = 4
    The Manager has taken a letter from the tray to sign, number signed = 4
    The Manager is ready to sign a letter
         etc
    Run your simulation until the secretaries have typed and filed 7 letters each, and the manager has removed and signed all 21 letters.
    Thanks again

    Then you're probably better off enlisting one-on-one, in-person help from your instructor, a classmate, or a private tutor, or joining a study group. Forums like this are not well-suited to tutoring you from the ground up.
    If you're doing multithreaded homework and you don't even know where to start, it sounds like ether the instructor is horrible or you're in over your head, or you just haven't been keeping up with the class.
    Good luck.

  • Using threads in a process of two or more tasks concurrently?

    Dear,
    I need to develop through a Java application in a process that allows the same process using Threads on two or more tasks can be executed concurrently. The goal is to optimize the runtime of a program.
    Then, through a program, display the behavior of a producer and two consumers at runtime!
    Below is the code and problem description.
    Could anyone help me on this issue?
    Sincerely,
    Sérgio Pitta
    The producer-consumer problem
    Known as the problem of limited buffer. The two processes share a common buffer of fixed size. One, the producer puts information into the buffer and the other the consumer to pull off.
    The problem arises when the producer wants to put a new item in the buffer, but it is already full. The solution is to put the producer to sleep and wake it up only when the consumer to remove one or more items. Likewise, if the consumer wants to remove an item from the buffer and realize that it is empty, he will sleep until the producer put something in the buffer and awake.
    To keep track of the number of items in the buffer, we need a variable, "count". If the maximum number of items that may contain the buffer is N, the producer code first checks whether the value of the variable "count" is N. If the producer sleep, otherwise, the producer adds an item and increment the variable "count".
    The consumer code is similar: first checks if the value of the variable "count" is 0. If so, go to sleep if not zero, removes an item and decreases the counter by one. Each case also tests whether the other should be agreed and, if so, awakens. The code for both producer and consumer, is shown in the code below:
    #define N 100                     / * number of posts in the buffer * /
    int count = 0,                     / * number of items in buffer * /
    void producer(void)
    int item;
    while (TRUE) {                    / * number of items in buffer * /
    produce_item item = ()           / * generates the next item * /
    if (count == N) sleep ()           / * if the buffer is full, go to sleep * /
    insert_item (item)                / * put an item in the buffer * /
    count = count + 1                / * increment the count of items in buffer * /
    if (count == 1) wakeup (consumer);      / * buffer empty? * /
    void consumer(void)
    int item;
    while (TRUE) {                    / * repeat forever * /
    if (count == 0) sleep ()           / * if the buffer is full, go to sleep * /
    remove_item item = ()           / * generates the next item * /
    count = count - 1                / * decrement a counter of items in buffer * /
    if (count == N - 1) wakeup (producer)      / * buffer empty? * /
    consume_item (item)      / * print the item * /
    To express system calls such as sleep and wakeup in C, they are shown how to call library routines. They are not part of standard C library, but presumably would be available on any system that actually have those system calls. Procedures "insert_item and remove_item" which are not shown, they register themselves on the insertion and removal of the item buffer.
    Now back to the race condition. It can occur because the variable "count" unfettered access. Could the following scenario occurs: the buffer is empty and the consumer just read the variable "count" to check if its value is 0. In that instant, the scheduler decides to stop running temporarily and the consumer starting to run the producer. The producer inserts an item in the buffer, increment the variable "count" and realizes that its value is now 1. Inferring the value of "count" was 0 and that the consumer should go to bed, the producer calls "wakeup" to wake up the consumer.
    Unfortunately, the consumer is not logically asleep, so the signal is lost to agree. The next time the consumer to run, test the value of "count" previously read by him, shall verify that the value is 0, and sleep. Sooner or later the producer fills the whole buffer and also sleep. Both sleep forever.
    The essence of the problem is that you lose sending a signal to wake up a process that (still) not sleeping. If he were not lost, everything would work. A quick solution is to modify the rules, adding context to a "bit of waiting for the signal to wake up (wakeup waiting bit)." When a signal is sent to wake up a process that is still awake, this bit is turned on. Then, when the process trying to sleep, if the bit waiting for the signal to wake up is on, it will shut down, but the process will remain awake. The bit waiting for the signal to wake up is actually a piggy bank that holds signs of waking.
    Even the bit waiting for the signal to wake the nation have saved in this simple example, it is easy to think of cases with three or more cases in which a bit of waiting for the signal to wake up is insufficient. We could do another improvisation and add a second bit of waiting for the signal to wake up or maybe eight or 32 of them, but in principle, the problem still exists.

    user12284350 wrote:
    Hi!
    Thanks for the feedback!
    I need a program to provide through an interface with the user behavior of a producer and two consumers at runtime, using Threads!So hire somebody to write one.
    Or, if what you really mean is that you need to write such a program, as part of your course work, then write one.
    You can't just dump your requirements here and expect someone to do your work for you though. If this is your assignment, then you need to do it. If you get stuck, ask a specific question about the part that's giving you trouble. "How do I write a producer/consumer program?" is not a valid question.

  • Using threads to change button status

    Hi all
    im reworking my conway life adt and trying to build it into an ap (as i have it working as an applet)
    as applets have a repaint command then implementing the generations was pretty easy.
    However in an application i will have to use threads wont i?
    so what i have done is built an ap that builds the life grid using swing buttons (this isnt a swing question by the way its a thread question :p)
    so how would i go about threading my application so it doesnt freeze up?
    here is the code from my swing ap
    import javax.swing.*;
    import java.awt.*;
    public class LifeAp
    private Life gLife;
    private JButton[][] buttons;
    private JFrame frame;
         public LifeAp(int y, int x)
         gLife=new Life(y,x);
         buttons=new JButton[y][x];
         for (int yc=0;yc<y;yc++)
              for (int xc=0;xc<x;xc++)
                   JButton btn=new JButton();
                   btn.setBackground(new Color(204, 204, 204));
                   btn.setText("");
                   buttons[yc][xc]=btn;
         initLife();
         public void buildForm()
         frame = new JFrame("Life");
         frame.getContentPane().setLayout
               (new GridLayout(buttons[0].length,buttons.length));
         for (int y=0;y<buttons.length;y++)
              for (int x=0;x<buttons[0].length;x++)
                   frame.getContentPane().add(buttons[y][x]);
         frame.pack();
         public void setButtons()
         for (int y=0;y<buttons.length;y++)
              for (int x=0;x<buttons[0].length;x++)
                   if (gLife.getStatus(y,x)==0)
                        buttons[y][x].setBackground(new Color(204, 204, 204));
                   else
                        buttons[y][x].setBackground(new Color(255, 255, 0));
         public void initLife()
         buildForm();
         gLife.generateMap();
         setButtons();
         public void show()
         frame.setVisible(true);
         private void exitForm(java.awt.event.WindowEvent evt)
         System.exit(0);
         public static void main(String[] args)
         new LifeAp(16,16).show();
    }the form builds just fine.
    now in the Life adt i have a method called generation()
    so when i call gLife.generation(); the next life phase is calculated
    so i need in a thread to basically say
    gLife.generation();
    setButtons();which will update life then colour the buttons accordingly.
    however i think that maybe im going to hit problems because of static and non static methods etc.
    have i approached this the wrong way? or is this something quite easy to implement into a thread?

    ok so now i have
         public void start()
         animator = new Thread(this);
         animator.start();
         public void run()
         long tm = System.currentTimeMillis();
         while (Thread.currentThread() == animator)
              gLife.generation();
              setButtons();
              validate();
              show();
              try
                   tm += delay;
                   Thread.sleep(Math.max(0, tm - System.currentTimeMillis()));
              catch (InterruptedException e)
                   break;
              frame++;
         }and my current main is
         public static void main(String[] args)
         LifeAp l=new LifeAp(64,64);
         l.show();
         l.start();
         }what should i have in my main code to start my thread?
    if i have
    public static void main(String[] args)
         LifeAp l=new LifeAp(64,64);
         l.show();
         }then the process doesnt run, it just displays the first generation then stops.
    so what do i need to include?

Maybe you are looking for