Why are the threads start and terminate randomly?

Hi there,
I got the program below. I am wondering why are the threads start and terminate randomly? Everytime, I run the program, it produces different results.
I know that these four threads have got same normal priority (should be 5), and under windows there is something called timeslice. Then these four threads rotate using this timeslice. How do we know what exactly the timeslice is in seconds? If the timeslice is fix, then why the results are ramdom?
Thanks in advance!
* To change this template, choose Tools | Templates
* and open the template in the editor.
package mythreadone;
* @author Administrator
public class MyThreadOne implements Runnable {
String tName;
Thread t;
MyThreadOne(String threadName) {
tName = threadName;
t = new Thread(this, tName);
t.start();
public void run() {
try {
System.out.println("Thread: " + tName);
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("Exception: Thread "
+ tName + " interrupted");
System.out.println("Terminating thread: " + tName);
public static void main(String args[]) {
// Why are the threads start and terminate randomly?
new MyThreadOne("1");
new MyThreadOne("2");
new MyThreadOne("3");
new MyThreadOne("4");
try {
Thread.sleep(10000);
// Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println(
"Exception: Thread main interrupted.");
System.out.println(
"Terminating thread: main thread.");
1. Firstly, I set in the main function:
Thread.sleep(10000);
and I run the program it gives:
Thread: 1
Thread: 4
Thread: 2
Thread: 3
Terminating thread: 1
Terminating thread: 3
Terminating thread: 4
Terminating thread: 2
Terminating thread: main thread.
BUILD SUCCESSFUL (total time: 10 seconds)
Run it again, it gives:
Thread: 2
Thread: 4
Thread: 3
Thread: 1
Terminating thread: 2
Terminating thread: 1
Terminating thread: 3
Terminating thread: 4
Terminating thread: main thread.
BUILD SUCCESSFUL (total time: 10 seconds)
And my question was why it outputs like this? It suppose to be:
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Terminating thread: 1
Terminating thread: 2
Terminating thread: 3
Terminating thread: 4
Terminating thread: main thread.
BUILD SUCCESSFUL (total time: 10 seconds)
Why these four threads start and finish randomly each time I run the program? I use Windows, suppose there is a timeslice (i.e. 1 second), these threads have the same priority. Then the threads should start and finish in turn one by one. Am I right?
2. My second question is:
When I change the codes in the 'main' function into:
Thread.sleep(10000); -> Thread.sleep(2000);
it gives me the results like:
Thread: 1
Thread: 4
Thread: 3
Thread: 2
Terminating thread: main thread.
Terminating thread: 1
Terminating thread: 4
Terminating thread: 3
Terminating thread: 2
BUILD SUCCESSFUL (total time: 2 seconds)
Run it again:
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Terminating thread: 3
Terminating thread: main thread.
Terminating thread: 4
Terminating thread: 2
Terminating thread: 1
BUILD SUCCESSFUL (total time: 2 seconds)
I tried several times. The main thread always terminates before or after the first child thread finished.
My question is why it doesn't output something like:
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Terminating thread: 3
Terminating thread: 4
Terminating thread: 2
Terminating thread: main thread.
Terminating thread: 1
BUILD SUCCESSFUL (total time: 2 seconds)
or
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Terminating thread: 3
Terminating thread: 4
Terminating thread: 2
Terminating thread: 1
Terminating thread: main thread.
BUILD SUCCESSFUL (total time: 2 seconds)

user13476736 wrote:
Yes, my machine has multi-core. Then you mean that if I got a one core machine the result should always be:
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Terminating thread: 1
Terminating thread: 2
Terminating thread: 3
Terminating thread: 4
Terminating thread: main thread.
BUILD SUCCESSFUL (total time: 10 seconds)
???No.
>
How to explain my second quesiton then? Why the main thread always terminates before some of the child threads end? Thanks a lot.

Similar Messages

  • Whats wrong, why doesnt the thread start?

    Below is my code for the part of my program, which creates a thread for every client that connects to a server in an instant messenger program. What the thread does it constantly recieves any data sent to the server, so that it therefore displays it on its own area of the screen. For some reason...this thread does not want to start. Any help would be incredibly appreciated. So heres the code:
    class SocketClient extends JFrame implements Runnable {
         Socket socket = null;
       PrintWriter out = null;
       BufferedReader in = null;
              String text = null;
              Thread getdata;
       SocketClient(){
         public void listenSocket() {
         if ( connected==("2") ) {
    //Create socket connection
         try{
           socket = new Socket("0.0.0.0", 4444);
                        System.out.println("Connected to self");
           out = new PrintWriter(socket.getOutputStream(), true);
           in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
         } catch (UnknownHostException e) {
           System.out.println("Unknown host: host your connecting to");
           System.exit(1);
         } catch  (IOException e) {
           System.out.println("No I/O");
           System.exit(1);
                   connected = "1";
         else {
              try{
                    socket = new Socket("0.0.0.0", 4444);
           out = new PrintWriter(socket.getOutputStream(), true);
           in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
         } catch (UnknownHostException e) {
           System.out.println("Unknown host: host your connecting to");
           System.exit(1);
         } catch  (IOException e) {
           System.out.println("No I/O");
           System.exit(1);
         if (thisclient==(1))
                   System.out.println("in thisserver");
                   Thread getdata = new Thread();
                             getdata.start();
                             thisclient = 2;
         senddata();
    public void senddata() {
         //Send data over socket
         System.out.println("in send data method");
         friendtypingLabel.setText("in send data");
              String text = messageArea.getText();
              out.println(text);
           messageArea.setText(new String(""));
    //Receive text from server
    public void run()
              if(getdata == Thread.currentThread() )
                   System.out.println("running getdata thread");  // if the thread was running this would be written to system but it isnt
                   friendtypingLabel.setText("running get data");
                   getdatamethod();
    public void getdatamethod() {
         //Send data over socket
    //Receive text from server
    while(true) {
           try{
           String line = in.readLine();
              messlistArea.append("Message Client:" + line + "\n");
           } catch (IOException e){
          System.out.println("Read failed");
                 System.exit(1);
              try { Thread.sleep(2000); }
                   catch(InterruptedException e) {}
    }

    k...well ive made it so that the client can see what they have just sent....but i cant seem to make is so that the can see wot the server and wot other clients have sent...here is some update code:
    class SocketClient extends JFrame implements Runnable {
         Socket socket = null;
       PrintWriter out = null;
       BufferedReader in = null;
              String text = null;
       SocketClient(){
         public void listenSocket() {
         if ( connected==("2") ) {
    //Create socket connection
         try{
           socket = new Socket("0.0.0.0", 4444);
                        System.out.println("Connected to self");
           out = new PrintWriter(socket.getOutputStream(), true);
           in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
         } catch (UnknownHostException e) {
           System.out.println("Unknown host: host your connecting to");
           System.exit(1);
         } catch  (IOException e) {
           System.out.println("No I/O");
           System.exit(1);
                   connected = "1";
         else {
              try{
                    socket = new Socket("0.0.0.0", 4444);
           out = new PrintWriter(socket.getOutputStream(), true);
           in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
         } catch (UnknownHostException e) {
           System.out.println("Unknown host: host your connecting to");
           System.exit(1);
         } catch  (IOException e) {
           System.out.println("No I/O");
           System.exit(1);
         if (thisclient==(1))
                   System.out.println("in thisserver");
                   getdata = new Thread(this);
                                                                                                                                                // if this is the client, then start the getdata
                             getdata.start();                                                                           // thread
                             thisclient = 2;
                             getdata.equals(Thread.currentThread());
         senddata();
    public void senddata() {
         //Send data over socket
         System.out.println("in send data method");
         friendtypingLabel.setText("in send data");
              String text = messageArea.getText();
              out.println(text);
           messageArea.setText(new String(""));
    //Receive text from server
    public void run()                                                   // runs the thread getdata
    System.out.println("Thread is " + Thread.currentThread());
              if(getdata.equals(Thread.currentThread()) )
                   getdatamethod();
    public void getdatamethod() {                      // method for the getdata thread
         //Send data over socket
    //Receive text from server
    while(true) {
    System.out.println("Run getdata");
           try{
                     String line = in.readLine();
                        if (line != null) {
              messlistArea.append("Message Client:" + line + "\n");
                             }catch (IOException e){
                              System.out.println("Read failed");
                      System.exit(1);
              try { Thread.sleep(2000); }
                   catch(InterruptedException e) {}
    }

  • Why are the printed image and its borders different than specified on Aperture's Print window

    Hi,
    I am trying to print an 11.98x17.97 image on a 13x19 sheet. I specify .51" borders top and bottom, and .52" right and left.
    Instead, I am getting a 7.5x10.75" printed image with L 1 1/8" + R 7 1/8" borders and T 1/8" + B 5 3/8" borders. In short, a smaller image, shoved up and left on the sheet. Please see screen shot below.
    Same happened when I tried to print a 4x6 image on an 8.5x11 sheet, until I was told by Kirby to enter the sheet size as a standard 'letter size' sheet instead of entering a custom 8.5x11" size. Is this the same? If so, what's the 'standard' size for 13"x19"?
    Something is going over my head here . HELP!
    RAPHAEL

    For the Epson 3880, I use the Paper Size "Super A3 / B 13 x 19 in (Manual — Rear)" when using Epson's 13x19" Hot Press or Cold Press paper.
    That's from my response to you on November 16th.  .
    That should allow you to print as you want.  I have a hunch about what might be happening with your current print setting, but I want to check it before speculating aloud.

  • Why are the Play, Previous, and Forward icons in iTunes unresponsive?

    I have all the updates. Everything works if I use the keyboard controls, but when I try to mouse over and click, it isn't responding everytime.
    Here is a video to explain what I mean:
    https://www.youtube.com/watch?v=f8y23C4SuUM

    If you do not see an item on a toolbar and in the toolbar palette then click the "Restore Default Set" button to restore the default toolbar set up.
    If the above steps didn't help then see:
    * http://kb.mozillazine.org/Corrupt_localstore.rdf

  • Why are the options for "When Firefox starts" NOT clickable in Firefox 5? I want to choose "Windows and tabs that where opened last time you accessed the net" but Firefox won't let me.

    In the previous version of Firefox one could choose to save tabs so that when Firefox opened, all the tabs from the previous sessions appeared. This was done in Settings > Options > General > Startup. In the menu for the "When Firefox Starts" one had the option for "Windows and tabs that where opened last time you accessed the net." in Firefox 5.0, this menu is gray and not clickable. Help, please?

    ''Why are the options for "When Firefox starts" NOT clickable in Firefox 5?"
    Possibly you are not saving your "browsing history" which is what the session history is tied into.
    '''Not saving History''' -- check your settings for '''Tools > options > Privacy'''', make sure you are not clearing more than just cache in "Settings for Clearing History"
    * http://img232.imageshack.us/img232/4928/clearcachew.png
    * clearing your history at end of session, cache is the only one you would want to clear at end of session, if you don't want to lose things
    There are several things that are related to private browsing and not saving History
    * Private Browsing Ctrl+Shift+P
    * You selected "Never remember history" in first drop-down of Tools > Options Privacy and all of the check marks disappear (See picture above)
    * "Permanent private browsing mode" was check-marked under "Use custom settings for history" in the first drop-down of Tools > options > Privacy (see picture above)

  • I've just started using the App Tabs. I think this feature could be handy but why are the sites not updated when I start Firefox. Now I have to manually update the site which is somewhat of a downer. Does any of you know where I'm going wrong?

    I've just started using the App Tabs. I think this feature could be handy but why are the sites not updated when I start Firefox. Now I have to manually update the site which is somewhat of a downer. Does any of you know where I'm going wrong?

    To answer the post title FireFox save all downloads automatically in the download folder, which you can find in the Documents folder. If you want to choose where to save your downloads go to tools>options>check always ask me where to save files.
    Secondly, I am assuming you have IE 8 installed as this is the only version that supports this fix that is currently not in beta. Go to control panel>internet options>advanced tab and reset the settings at the bottom. This may or may not fix the problem but it is a good first step.

  • Why is the music on my iPod randomly not letting me play? all my good ones are the ones I purchased won't play, my storage is fine. I tap on the song but it skips to a completly different song on iPod but not laptop

    Why is the music on my iPod randomly not letting me play? all my good ones are the ones I purchased won't play, my storage is fine. I tap on the song but it skips to a completly different song on iPod but not laptop. For example both versions of Til' I Collapse by Eminem won't play on my iPod but on laptop, same with Born this Way by Lady Gaga

    Try:
    - Reset the iOS device. Nothing will be lost
    Reset iOS device: Hold down the On/Off button and the Home button at the same time for at
    least ten seconds, until the Apple logo appears.
    - Unsync all music and resync
    - Reset all settings
    Go to Settings > General > Reset and tap Reset All Settings.
    All your preferences and settings are reset. Information (such as contacts and calendars) and media (such as songs and videos) aren’t affected.
    - Restore from backup. See:                                 
    iOS: How to back up           
    - Restore to factory settings/new iOS device.

  • How come although iPads are getting more powerful, the iOS apps from apple are so mediocre and just not that great? We spend all this money for the latest ipad and all we get is these $5 video and music apps from apple. Why create the iOS platform and onl

    How come although iPads are getting more powerful, the iOS apps from apple are so mediocre and just not that great? We spend all this money for the latest ipad and all we get is these $5 video and music apps from apple. Why create the iOS platform and only offer so so apps like IMovie and GarageBand ? While other developers are offering much better apps like pinnacle studio for video, Cubasis and Auria for music production, apple has not showed much growth in terms of innovation. While there's nothing wrong with making an app like GarageBand where "anyone " can make a song, how about something for real musicians or an app not so basic as it get for video editing? After spending 0ver $700 on an ipad I'd be willing to spend more than $5 for a better video or audio app.

    First, try a system reset although I can't give you any confidence.  It cures many ills and it's quick, easy and harmless...
    Hold down the on/off switch and the Home button simultaneously until you see the Apple logo.  Ignore the "Slide to power off" text if it appears.  You will not lose any apps, data, music, movies, settings, etc.
    If the Reset doesn't work, try a Restore.  Note that it's nowhere near as quick as a Reset.  It could take well over an hour!  Connect via cable to the computer that you use for sync.  From iTunes, select the iPad/iPod and then select the Summary tab.  Follow directions for Restore and be sure to say "yes" to the backup.  You will be warned that all data (apps, music, movies, etc.) will be erased but, as the Restore finishes, you will be asked if you wish the contents of the backup to be copied to the iPad/iPod.  Again, say "yes."
    At the end of the basic Restore, you will be asked if you wish to sync the iPad/iPod.  As before, say "yes."  Note that that sync selection will disappear and the Restore will end if you do not respond within a reasonable time.  If that happens, only the apps that are part of the IOS will appear on your device.  Corrective action is simple -  choose manual "Sync" from the bottom right of iTunes.
    If you're unable to do the Restore, go into Recovery Mode per the instructions here.

  • The ipad won't sync some photos, saying the file can't be read by the ipad, however it will sync some photos taken at the same time which are the same size and file type.  Why does it reject some and accept others?

    The ipad won't sync some photos, saying the file can't be read by the ipad, however it will sync some photos taken at the same time which are the same size and file type.  Why does it reject some and accept others?

    Hi there. I'm having the same problem: my iPad won't import some photos from a folder, saying that they can't be read. They are all JPEGS and some photos taken at the same time have synched fine, but out of a folder with 200 photos, it only lets me synch 37. I'm synching albums created via Photoshop Elements 6, which has worked fine until now.
    I've tried deleting all photos and re-synching, and have also deleted the iPod Photo Cache, but it hasn't made a difference.
    The iPad auto-updated to the latest version of iTunes, so maybe that's what's causing it?
    Any advice gratefully received!

  • Why are all my movies and tv shows now on my ipad with the icloud icon?  How can i get rid of them?

    Why are all my movies and tv shows from my library now on my ipad with the icloud icon?  I have turned off all icloud related services. I have never used it.  On top of that, my ipad now gets stuck on step 5 of the sync - waiting for changes to be applied and never finishes.
    Help

    Hi, go in Settings, under Videos turn off "Show all videos"  this will remove the purchased videos to be displayed in the Video app.  The same can be done with the music.
    As for Step 5, connect you iPad and on the summary Tab, uncheck
    "Sync only checked songs and videos".  Then wait, it takes a while but this made it work for me after many restore attempts.
    good luck

  • Why are the apps on my IPad scattered across the whole thing and when I open them they turn to little rectangles in the corner of the screen and I can't even use them or tap on anything. Also when I turn my iPad it doesn't flip the screen over

    Why are the apps on my IPad scattered across the whole thing and when I open them they turn to little rectangles in the corner of the screen and I can't even use them or tap on anything. Also when I turn my iPad it doesn't flip the screen over.

    Hi The next thing to do is to Restore back to Factory Settings this will get rid of any bugs . After Restore use same Apple ID /Password then you should get all your Apps & data back If you still have this problem make an Appointment at Apple Store . Cheers Brian

  • Why does the video stop and start using airplay on Mountain Lion?

    Why does the picture stop and start using airplay on Mountain Lion? I'm playing a film from a website and uising airplay to iTV. The sound is fine, but the picture stops and starts. Any ideas?

    Why does the picture stop and start using airplay on Mountain Lion? I'm playing a film from a website and uising airplay to iTV. The sound is fine, but the picture stops and starts. Any ideas?

  • My time capsule is full and when I attempt to back up, I only receive a preparing back up message and the earliest and most recent back up dates remain the same.  Why are the oldest backups not being deleted to make room for the newest backups?

    My time capsule is full and when I attempt to back up, I only receive a preparing back up message and the earliest and most recent back up dates remain the same.  Why are the oldest backups not being deleted to make room for the newest backups?

    linda mariefromharper woods wrote:
    My time capsule is full and when I attempt to back up, I only receive a preparing back up message and the earliest and most recent back up dates remain the same.  Why are the oldest backups not being deleted to make room for the newest backups?
    It may be in the process of making room.  What version of OSX are you on?    (That process can be excruciatingly slow on Leopard or Snow Leopard backups over a network;  Lion has improved it greatly.)
    A clue may be lurking in your logs.  Use the widget in #A1 of  Time Machine - Troubleshooting to display the backup messages from your logs.   That should help you figure out what's going on.  If in doubt, copy and post them here (but if the same ones repeat over and over, drop most of the duplicates).
    If you can, connect via Ethernet; it will be 2-3 times faster.

  • Why are the songs in my iphone playlists grey and I can't move them.

    Why are the songs in my iPhone playlists grayed out.  I am unable to move and organize them.  I just downloaded some audio books from Audible and I cannot moved them to a playlist on my iPhone either.  What step am I missing?

    margielm2 wrote:
    So, if I haven't made any albums, I can't move pictures in the main window of the Organizer?
    Yes, you can't. The default order in the main window is based on date, ascending or descending when you are in the standard 'thumbnail view'. If you are in 'folder' view, with your folders shown in the left panel, you are shown the pictures in alphabetical order of the file names.
    I haven't created albums yet.
    I have so many pictures. I wanted to put all the pictures for each album next to each other so I can find them easily.
    It's not difficult to create albums and 'drag' pictures in it. When an album is selected, you can move your pictures around in any order in the main window panel.
    Albums are one way of grouping and ordering pictures. You should try to use keywords to organize and retrieve your pictures.

  • Why are the songs downloaded from my computer grayed out and won't play?

    Why are the songs that I downloaded from my pc not playing on my iphone and grayed out?

    Hi sweatt,
    Welcome to Apple Support Communities.
    You may find these steps helpful for resolving the issue you're encountering:
    iTunes Store: Troubleshooting iTunes Match
    http://support.apple.com/kb/ts4054
    Songs containing DRM (Digital Rights Management) may not appear, or may appear grayed out in iCloud. This can occur if your computer is not authorized for playback of that content. Try authorizing your computer, then manually update iTunes Match.
    To determine what Apple ID your computer needs to be authorized for, locate and select the song in your iTunes library.
    Choose File > Get Info.
    In the Summary tab, locate the Account Name field in the right column and write it down.
    Click OK.
    Choose Store > Authorize this Computer.
    Type in the account name from the Summary field and its password. Click Authorize.
    Choose Store > Update iTunes Match.
    Best,
    Jeremy

Maybe you are looking for

  • Taget disk mode with lid closed?

    I'd like to connect my uni-body MBP to my Mac Pro. Is it OK to go into Target Disc Mode, connect a firewire cable and closed the lid? I'd like to be able to place the MBP in my BookArc while I transfer/sync data this way. I'll have the power adapter

  • Data gets not saved?

    Hi i am new at programming and also i am dutch so my english is not that high quality. sorry for that. reading is a lot better than writing ;) So here is my problem (i use visualstudio 2013 express) my goal is to design a desktop app that keeps track

  • Problems recovering SYSAUX

    Dear All I have a 10g database running on redhat EL 4.2. This morning I tried to run a flashback query on one of the tables only to be told there was a problem with one of the datafiles. Further investigation showed this to be the datafile containing

  • Setting Inter VLAN in the Router.

    Hi, I trying to set up inter VLAN on the Cisco 2651XM router. I try to type the IP address on the sub interface but it gives me an error. I need to set up first the encapsulation dot1 q. I type encapsulation command but it doesn't recognized. This is

  • Problem in migrating huge data from mysql to oracle using OMWB.

    I'm using OMWB to migrate my mysql db to oracle db.Mysql db contains some 43 tables and all of them were copied to oracle db except a table "as_db" which contains some 503 mb of data.The table contains 3 columns and two of them were integer type and