May threads force other threads to sleep?!

Hi all,
Really hope someone may help me!! I have four classes. The master program, class A, calls class B (not a thread) when an action occurs. The actions effect the behaviour of the third class ObjectThread. B may sometime force the ObjectThread thread to sleep for some time (not predetermined). Then when it's time, B awakens ObjectThread, which continues.
The problem is that I don't want B to lock while an ObjectThread is sleeping. Hence I have created class C (also a thread), which is called only when ObjectThread needs to sleep. Input to C is a handle to the respective ObjectThread. But I can't get class C to force ObjectThread to sleep! I've tried not having C as a thread, but merely as a simple class, then it works but the whole thing locks.
How can I make the C thread perform first:
handleToObjectThread.sleep (); (this I guess may be managed with while loops)
then whenever I feel like it in the B class
handleToObjectThread.interrupt ();
Please help!!
/ jez

i assume that ObjectThread has a loop in its run() method...
why not at the start or end of the loop, get it to check to see if it should be sleeping
then class B could just set a flag (boolean) or an int (time to sleep) in ObjectThread
so..
ObjectThread extends Thread{
private boolean sleep=false;
public void run(){
  while(doit){
   if(sleep){
    try{
     while(!sleep){
      Thread.sleep(whatever);
    catch(InterruptedException ie){};
   //rest of loop
public void goToSleep(){
  sleep=true;
public void wakeUp(){
  sleep=false;
interrupt(); // only if you need to wake immediately
}

Similar Messages

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Sending a thread to sleep

    I want to send a thread to sleep, but from another one.
    sleep() method is static and send the current thread, so it doesn't work for me...!
    T.I.A.

    Ok, you can add some methods to ClsListener that looks something like this:
    boolean sleep = false;
    long delay = 0;
    public synchronized void putToSleep(long delay) {
      sleep = true;
      this.delay = delay;
    public synchronized void wakeUp() {
      notify();
      sleep = false;
    private void checkShouldSleep() {
        if (sleep) { // test if I should sleep
          synchronized (this) {
            if (sleep) { // to be absolutely sure the wakeUp method hasn't been called before put to sleep
              try { wait(delay); } // delay = 0 means sleep forever or until the wakeUp method has been called (or interrupted)
              catch (InterruptedException e) {}
    public void run() {
      while (true) {
        // the threads task..
        checkShouldSleep(); // check this as often as you want
    }Now you just call putToSleep or wakeUp on your ClsListeners.

  • Force other users to logout

    I can I force a logout of a managed user when using fast user switching?

    Matti Haveri wrote:
    Thanks for the tip nerowolfe.
    I also miss an easy way to logout other users. My son and daughter sometimes leave Safari, Messenger etc open in their accounts so they unnecessary consume the CPU so that the fans may even turn on although my active account is idling.
    Rebooting the system does the trick but it takes time and then I have to login and open my applications.
    So I miss the "clean logout of other users with no rebooting" - option.
    So does shutdown -r force other users besides me to logout?
    The shutdown command I gave will log out all users and restart the computer. It was a "scare" tactic
    However,
    shutdown -k
    with "k" for kick off" will remove all users, including yourself, but will not reboot the machine, so all you have to do is log in again, but I am not sure how because:
    The manual says:
    Kick everybody off. The -k option does not actually halt the system, but leaves the system multi-user with logins disabled (for all but super-user).
    So it may not be a good method after all.
    As an administrator you should be able to log into the other accounts and log them off manually. That's probably the best way.

  • Is there a option to allow firefox to work better with other aplication in fullscreen mode, becouse in present FF force other app to hide

    Is there any way so FF in full screen mode do not force other application to hide? i would like to use full screen mode more often but for instance it force my winamp to hide and i cant switch music or use any other app that i would like to at the same time when I'm browsing the web. I think it would be very usefull for many ppl who brows pictures etc. and for navigation they use mouse commands.
    Thanks.

    offcorse i know that but fullscreen mode hide status bar, tabs etc and show it when i move my mouse on it and thats why i like it it hide all what i dont need but i need winamp and switchin alt tab all the time its not fun when in can be placed on the down corner, when wimamp skin is transparent. i woud like to have such a option (for instance in about:config.

  • Force other Windows to close

    In my Oracle Form, the users can select items from the menu and open a new Window in the application. There is a danger that they could get too many Windows open and slow down the application.
    Is there a way to force other Windows to close when they open a new one?
    Thanks

    Check out the call new_form. If that doesn't work for your situation you will have to maintain a global variable of opened windows and close the one the user came from.

  • Tips on Nokia 6233!! Pls read. May apply to other ...

    I have the excellent Nokia 6233. I have created a guide on how to optimize your experience with the Nokia 6233. It may work with other phones as well. Enjoy! Please go to:
    6233 Guide

    I have the excellent Nokia 6233. I have created a guide on how to optimize your experience with the Nokia 6233. It may work with other phones as well. Enjoy! Please go to:
    6233 Guide

  • Menu and Thread.sleep(5000) or Thread.currentThread.sleep(5000)

    Hi,
    I am using JMenu and switchable JPanels.
    When I click on a MenuItem the follownig code should starts
        cards.add(listenPanel,  "listenPanel");
        cardLayout.show(cards, "listenPanel");
        try{
          Thread.sleep(5000); //in ms
          PlayMP3Thread sound = new PlayMP3Thread("sound/ping.mp3");
        } catch(Exception e) {
          e.printStackTrace();
        }It seems to be what I want to reach, but it does not work the way I want it to.
    I would like the Panel to show right away, then wait 5s and then play the sound.
    BUT what it does is freez the unfolded menu for 5s, then plays the sound and after that it shows the new Plane.
    Can you tell me why this is??

    This might be what you want
    package tjacobs.thread;
    import java.awt.Dimension;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.concurrent.Semaphore;
    import tjacobs.ui.Eyes;
    import tjacobs.ui.util.WindowUtilities;
    public class ThreadForMultipleAnytimeRuns extends Thread {
         private Runnable mRunnable;
         private Semaphore mSemaphore;
         public ThreadForMultipleAnytimeRuns(Runnable arg0) {
              super();
              init(arg0);
         private void init(Runnable r) {
              mRunnable = r;
              mSemaphore = new Semaphore(0);
              setDaemon(true);
         public ThreadForMultipleAnytimeRuns(Runnable arg0, String arg1) {
              super(arg1);
              init(arg0);
         public ThreadForMultipleAnytimeRuns(ThreadGroup arg0, Runnable arg1, String arg2) {
              super(arg0, arg2);
              init(arg1);
         public void run () {
              try {
                   while (!isInterrupted()) {
                        mSemaphore.acquire();
                        mRunnable.run();
              catch (InterruptedException ex) {}
         public void runAgain() {
              mSemaphore.release();
         public void runAgain(int numTimes) {
              mSemaphore.release(numTimes);
         public void stopThread() {
              interrupt();
         public int getSemaphoreCount() {
              return mSemaphore.availablePermits();
         public Runnable getRunnable() {
              return mRunnable;
         //The setRunnable method is simply not safe, and
         //trying to make it safe is going to effect performance
         //Plus I can't really see a gain in being able to set
         //The runnable on one of these threads. Just create
         //a new one!
         public synchronized void setRunnable(Runnable r) {
              if (getSemaphoreCount() > 0) {
                   try {
                        wait();
                   catch (InterruptedException ex) {
                        return;
              mRunnable = r;
         public static void main(String[] args) {
              final Eyes eyes = new Eyes(true);
              //eyes.addMouseMotionListener(eyes);
              Runnable r = new Runnable() {
                   public void run() {
                        eyes.blink();
                        try {
                             Thread.sleep(100);
                        catch(InterruptedException ex) {}
              final ThreadForMultipleAnytimeRuns ar = new ThreadForMultipleAnytimeRuns(r);
              ar.start();
              eyes.addMouseListener(new MouseAdapter() {
                   public void mouseClicked(MouseEvent me) {
                        ar.runAgain();
              eyes.setPreferredSize(new Dimension(60,20));
              WindowUtilities.visualize(eyes);
    //          JFrame jf = new JFrame();
    //          jf.add(eyes);
    //          jf.pack();
    //          jf.setLocation(100,100);
    //          jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //          jf.setVisible(true);
    }

  • Thread.currentThrread().sleep(10) or Thread.sleep(10) ?

    what's the difference between the 2 calls to sleep() ?
    thanks.

    They call the same method (because sleep is static) even if you call sleep on a different thread the current thread executing the code will sleep

  • Sending threads to sleep

    writing w = new writing("     ");
         Thread t = new Thread(w);
        t.start();t.setName("1");
        t.sleep(100);this code here is creating an instance of writing which processes the threads then i go onto create the thread start it and set its name. when i try to send it to sleep though it wont compile.
    static void      sleep(long millis) is the type of the method i am calling
    it says it has an error unhandled exception type InteruptedException
    does anyone know how to get it to work?

    this is what i have
    try{
         writing w5 = new writing("                                ");
         Thread t5 = new Thread(w5);
         t5.start();t5.setName("6");     
        t5.sleep(100);}
         catch (Exception e){}
         }it compiles but have i done it right?

  • Thread's sleep method

    It takes darn miliseconds... any conversions on how many milliseconds = 30 minutes?
    I tried to search and got no where...

    And you don't even have to do the math. IIRC, if you use constants and numeric literals, the compiler will do the math and put a constant value equal to the value of the expression in the class.
    int thirtyMinutes = 1000 * 60 * 30;  // 1000 milliseconds per second, 60 seconds per minute, 30 minutes
    // compiler puts 1,800,000 in the final class fileIt's easier to read that way anyway.

  • Forcing External Drives To Sleep

    Greetings:
    Subject line says it all; how can I force my external drives to sleep? My LaCie Quad does so instantly when unmounted via Disk Utility but my IBM DeskStars keep running no matter what. Much appreciate any help!
    JimWG

    Hi James, a lot of that is going to be controlled the the HD itself, and/or the chipset used in the case, but these may help you accomplish it...
    http://lowendmac.com/musings/06/0217.html
    http://forums.macrumors.com/showthread.php?t=253301

  • Mountain Lion on iMac with no SSD - why is Power Nap forcing my computer to sleep?

    I have an iMac purchased in mid-2011.  It has no SSD.  So why is it going to sleep when tasks are still running?  If I'm encoding a video in HandBrake, downloading files in Firefox or Chrome, etc...the computer goes to sleep, despite the fact that it's still doing something.  Why is this?  If my iMac is not Power Nap capable, shouldn't it use the old method for determining whether or not to go to sleep?  Why can't we choose between Power Nap and previously functioning sleep behavior?

    Lanny wrote:
    Maybe this will help: http://forum.serviio.org/viewtopic.php?f=5&t=7791
    I am unclear on how that will help.  It is a link to a post from a user on a non-Apple website whose first and only post is about how this problem exists.  And I assume if you're referring to the Apple Discussion thread that other post links to, you would have just posted that link instead. 
    If you intended to link to that other Apple Discussion thread, from that discussion thread, Apple told one user, "Apps need to use power assertions while engaged on activities that should not be interrupted and we are working to evangelize this." meaning that Apple realizes they haven't done a good job of letting developers know of this; and that was from October 18, 2012, nearly 3 months after Mountain Lion's release date and I believe nearly 8 months after the first developer preview.  So by Apple's own admission they haven't done a good job regarding this issue.
    However, that does explain why Mountain Lion is behaving the way it did.  Both Apple and developers dropped the ball on this given that major apps (Firefox, Chrome, etc...) still don't implement Apple's new method of power saving.

  • How to force the display to sleep, while keeping the computer running?

    I'm running some compression and transcoding programs on my iMac G5 (iSight) that keeps the CPU at 100% for hours at a time. My Energy Saver prefernces is set to sleep the display after a few minutes, but never to sleep the computer or the hard disk.
    Like I'd expect with such a high CPU load, my computer's screen does not go to sleep.
    Is there a program or command line utility that I can run to force my screen to go to sleep, but keep the computer running?
    iMac G5 17" (iSight)   Mac OS X (10.4.5)  

    To put your display only to sleep;
    Go to System Preferences, click on 'energy saver', check the 'Put the display to sleep when the computer is inactive for' box, and then set the time. Note; this just puts the display to sleep, not the whole computer. Your hard disk will keep running. I find this much more convienent than putting the computer in 'full sheep'. It wakes up much quicker without some of the hassle some computers display coming up from full sleep.

  • Is there a way to force other accounts to log off?

    Hi, I see older posts on this but nothing new, and I was hoping maybe newer versions of Mac OS X have solved this.  I have a big family, and often my kids forget to log out of their accounts; eventually, the machine slows to a crawl for all the apps they collectively leave open.  Is there a way to automatically force accounts to log off after a certain amount of idle time, or a way for me to "bulk" log them off?  Restarting the machine or individually logging into each account is one way to do it, but it sure is inconvenient when all I want to do is hop on for five minutes to check email etc.  Thanks in advance for any suggestions.

    Another option is to set a idle-session timeout in System Preferences > Security & Privacy > General > Advanced, but that will affect all users, including you.

Maybe you are looking for

  • Building a Composite Business Process from Scratch-Guided 1 (Cannot Build)

    Hi, I have tried to followed the document : Building a Composite Business Process from Scratch with SAP NetWeaver BPM u2013 Guide 1 to create my first BPM program, however, the program cannnot be built. I don't knoww how to fix the program, can you h

  • How to maintain the date fromat in DD.MM.YY

    Hi I want maintain the date fromat like DD.MM.YY i have used following statement but it is showing systax error. please send the solution for this asap          write: i_vbrk-erdat to v_erdat dd.mm.yy. regards venu

  • Convert "Grayscale I16" to "RGB U64"

    Hello,  I need to convert an image from Grayscale I16 to RGB U64, but it doesn't work (I have joined a zip file). I think there is a bug in the NI Vision, or it's not implemented because I have no problem to do it from Grayscale U8 to RBG32.  Can you

  • How do I set the printer to default in fast mode?

    I want my printer to default to the fast mode rather than standard; as it is I have to adjust it for each document.  How do I do that?

  • Elements 10 error 213:11?

    Sorry I couldn't find a search function in the forum and since this is the error I am advised to go to Adobe with, I expect it is a standard error, but i need assistance. I have installed, but on start up I get this error.  I restarted pc but no chan