Why do threads run one at a time?

[Newbie] Couldn't get help in another forum, so here goes. Tried this in Netbeans 3.5 then at home later in BlueJ, same thing. Thanks in advance!
I have written a small application to play with threads. I create 3 instances of a class and shoot each one off in a thread, but they all seem to run one at a time, not at the same time. I have posted the code below. The output I expect is something like this:
0T1
0T2
0T3
1T1
1T2
1T3
2T1
2T2
2T3
498T1
498T2
498T3
499T1
499T2
499T3
500T1
500T2
500T3
The T1 means threadstart1 wrote that line, the T3, means threadstart3 wrote the line, etc. I would expect to see these slightly out of order, too, knowing that the threads will process what they can, when they can. Instead, I see this:
0T1
1T1
2T1
500T1
0T2
1T2
2T2
500T2
0T3
1T3
2T3
500T3
It's in perfect numeric order, each completing before the next starts. What am I doing wrong?
//-------------dostuff.java
package delme2;
public class dostuff implements Runnable {
private String mtext;
public dostuff(String atext) {
mtext = atext;
public void run() {
int j;
String s;
//display 500 numbers
for (j=0; j<500; j++) {
//build the string
s = String.valueOf(j) + mtext;
//show the string
System.out.println(s);
//wait a bit before doing this again.
try {
Thread.sleep(10);
} catch (InterruptedException e) {
//--------------- delme2.java
package delme2;
public class delme2 {
public delme2() {
System.out.println("Thread demo:");
Runnable threadstart1 = new dostuff("T1");
Runnable threadstart2 = new dostuff("T2");
Runnable threadstart3 = new dostuff("T3");
Thread t1 = new Thread( threadstart1 );
Thread t2 = new Thread( threadstart2 );
Thread t3 = new Thread( threadstart3 );
t1.run();
t2.run();
t3.run();
public static void main(String[] args) {
delme2 mydelme2 = new delme2();
}

Okay, I'll play along. Having written a task scheduler in C (under tutorial, I admit), I think I qualify. A task scheduler has three jobs at all times.
1) Execute the code at hand.
2) Figure out when to stop executing the code at hand.
3) When stopped, figure out what code to execute next.
When executing a piece of code, there are different paradigms for determining when to stop and move on. Ideally, a cooperative multitasking system would have threads that relinquish timeslices or have some other method sprinkled throughout their code that indicates to the task scheduler that it's okay to move on to another piece of code. In my experience, that indicator is a Thread.Sleep() or equiavalent. when the thread.sleep() is encountered. The task scheduler has nothing to do for a whopping 10 MS. It could even take 15 or 20 ms if the next process in line takes that long. So what is it doing for 10 ms? It's not executing those other threads, which should be queued for their turn on step #3 as soon as I fire them off with a .run().
Now, I hope you can see that I've given this some thought and read about it, but I'm missing something. I can get a very similar project to work as I expect it to in .NET and in Delphi. The Java environment has something different about it that I haven't figured out. Here's the c# code that does EXACTLY what I want it to. All threads run at a same time, and I get 0,0,0,1,1,1,2,2,2,3,3,3,4,4,4, etc.. See the similarities?
          private void button1_Click(object sender, System.EventArgs e)
               lst.Items.Clear();
               ThreadStart start1 = new ThreadStart(runner);
               ThreadStart start2 = new ThreadStart(runner);
               ThreadStart start3 = new ThreadStart(runner);
               Thread t1 = new Thread(start1);
               Thread t2 = new Thread(start2);
               Thread t3 = new Thread(start3);
               t1.Start();
               t2.Start();
               t3.Start();
          private void runner()
               string s;
               for (int j=0; j<500; j++)
                    s = j.ToString();
                    lst.Items.Add(s);
                    Thread.Sleep(10);
          }

Similar Messages

  • Is it possible to have 2 threads running at the same time?

    Is it possible to have 2 threads running at the same time at different times eg 1 repeats every 20 miliseconds and the other 40 for example. Also could you have 2 run() methods in one script, in one file? If so how? Help soon would be appreciated. Thanks.

    Is it possible to have 2 threads running at the same
    time at different times eg 1 repeats every 20
    miliseconds and the other 40 for example. Yes.
    http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html

  • I uninstalled Firefox once, reinstalled it and it ran. I had a problem so I did it again. Now it will not run and I get an error message saying that firefox is running and you can only run one at a time. I can't figure out what is running.

    Because of a problem, I uninstalled Firefox once, reinstalled it and it ran. I had a problem so I uninstalled/reinstalled it again. Now it will not run. I get an error message saying that firefox is running and you can only run one at a time. I have uninstalled multiple times and can't figure out what is running. The is only one Firefox installed and it is not open. What does this mean and how do I fix it?

    If you use ZoneAlarm Extreme Security then try to disable Virtualization.
    *http://kb.mozillazine.org/Browser_will_not_start_up#XULRunner_error_after_an_update
    See also:
    *[[/questions/880050]]

  • Thread Running negative number of time.

    Hi All,
    I wrote a program to check the effects of Thread priority, however to my surprise the output is weired the higher priority thread shows that it run negative number of time, below is the code.
    package javaProg.completeReferance;
    class Clicker implements Runnable
         Thread t;
         int click;
         volatile boolean  running = true;
         public Clicker(int pro)
              t=new Thread(this);
              click = 0;
              t.setPriority(pro);
         public void run()
              while (running)
                   click++;
         public void start()
              t.start();
         public void stop()
              running=false;
    public class TestClicker
         public static void main(String [] args)
              Clicker thread1 = new Clicker(Thread.NORM_PRIORITY+2);
              Clicker thread2= new Clicker(Thread.NORM_PRIORITY-2);
              thread1.start();
              thread2.start();
              System.out.println("Processing");
              try
                   Thread.sleep(10000);
              catch (InterruptedException i)
                   System.out.println(i);
              thread1.stop();
              thread2.stop();
              try
                   thread1.t.join();
                   thread2.t.join();
              catch (InterruptedException i)
                   System.out.println(i);
              System.out.println("The number of Time Thread1 executed is "+thread1.click);
              System.out.println("The number of time Thread2 executed is "+thread2.click);
    }Here is the Output..
    C:\Users\pravin>java javaProg.completeReferance.TestClicker
    Processing
    The number of Time Thread1 executed is -386946835
    The number of time Thread2 executed is 837375311Thanks!!

    Thanks a lot , I changed int click to long and its
    working fine.I am wondering why the Java Platform
    didnt throw an error or exception for overflow.Because the Java specification calls for it not to do that but instead to do what you saw and rollover.

  • Please help me figure out why this thread's performance degrades over time

    Hello.
    The code below is from a Runnable that I've tested inside a Thread operating on a TreePath array of size 1500; the array 'clonedArrayB' is this TreePath array. The code is designed to create a more stepped version of setSelectionPaths(TreePath[]) from class JTree.
    The performance decrease of the thread is very rapid; this is discernible simply from viewing the println speed. When it gets to about 1400 TreePaths added to the JTree selection, it's running at roughly 1/10 the speed it started running at.
    I know there's no problem with maintaining a set of selected paths of that size inside a JTree. I also know that the thread stops when it should. So it must be some operation I'm performing inside the brief piece of code shown below that is causing the performance degradation.
    Does anyone have any idea what could be causing the slowdown?
    Many thanks for your help. Apologies if you would have liked an SSCCE, but I very much doubt it's necessary for this. Either you can see the problem or you can't. And sadly I can't x:'o(
    int indexA = 0;
    public void run() {
         // Prevent use of / Pause scanner
         try {
              scannerLock.acquire();
         } catch (InterruptedException exc) {
              Gecko.logException("Scanner lock could not be acquired by expansion thread", exc);
         while (!autoExpansionComplete) {
              while (indexA < clonedArrayA.length) {
                   int markerA = indexA + 10;
                   for (int a = indexA; a < markerA && a < clonedArrayA.length; a++) {
                        pluginTreeA.addSelectionPath(clonedArrayA[a]);
                   indexA = markerA;
                   System.out.println(indexA + "," + clonedArrayA.length);
                        if (autoExpansionComplete) {
                             break;
                   stop();
    };

    Well, since I've had no responses, I tried to think of other ways to speed the code up.
    I'd already made nearly every tweak I know. The only additional thing I could think of was to use addSelectionPaths(TreePath[]) on a subarray of the cloned array, instead of addSelectionPath(TreePath) on the cloned array's elements, since obviously it would be fewer method calls. It has sped things up an awful lot (my new code is shown below - I've left in some things I chopped out above, so you can see exactly what I see). The problem is though, obviously an increase in initial velocity doesn't solve the problem of deceleration occurring, if you get me.
    // Clone the selection arrays to non-volatile arrays for better access
    // speeds
    final TreePath[] clonedArrayA = selectionPathsArrayA.clone();
    final TreePath[] clonedArrayB = selectionPathsArrayB.clone();
    // Create a new runnable to perform the selection task
    Runnable selectionExpander = new Runnable() {
         /** Position within cloned array A */
         int indexA = 0;
         /** Position within cloned array B */
         int indexB = 0;
         /** Length of subarray grabbed from cloned array A */
         int lengthA;
         /** Length of subarray grabbed from cloned array B */
         int lengthB;
         /** Subarray destination */
         private TreePath[] subarray = new TreePath[100];
         public void stop() {
              autoExpansionComplete = true;
              automatedSelection = false;
              scannerLock.release();
          * Grabs 10 blocks of each selection paths array at a time, adding
          * these to the tree's current selection and then moving to the next
          * cycle
         public void run() {
              // Prevent use of / Pause scanner
              try {
                   scannerLock.acquire();
              } catch (InterruptedException exc) {
                   Gecko.logException("Scanner lock could not be acquired by expansion thread", exc);
              while (!autoExpansionComplete) {
                   while (indexA < clonedArrayA.length || indexB < clonedArrayB.length) {
                        // Set subarray lengths
                        lengthA = subarray.length;
                        lengthB = subarray.length;
                        // If subarray length is greater than the number of
                        // remaining indices in the source array, set length to
                        // the number of remaining indices
                        lengthA = indexA + lengthA > clonedArrayA.length ? clonedArrayA.length - indexA : lengthA;
                        lengthB = indexB + lengthB > clonedArrayB.length ? clonedArrayB.length - indexB : lengthB;
                        // Create subarrays and add TreePath elements to trees'
                        // selections
                        System.arraycopy(clonedArrayA, indexA, subarray, 0, lengthA);
                        pluginTreeA.addSelectionPaths(subarray);
                        System.arraycopy(clonedArrayB, indexB, subarray, 0, lengthB);
                        pluginTreeB.addSelectionPaths(subarray);
                        // Remember the latest index reached in source arrays
                        indexA += lengthA;
                        indexB += lengthB;
                        System.out.println(indexA + "," + clonedArrayA.length);
                        System.out.println(indexB + "," + clonedArrayB.length);
                        if (autoExpansionComplete) {
                             break;
                   stop();
    // Create and start new thread to manage the selection task runner
    selector = new Thread(selectionExpander);
    selector.start();I really can't think what could be causing the slowdown. I've done everythng I can think of to increase the velocity, such as cloning the source arrays since they're volatile and access could be slightly slower as a result.
    Nothing I try gets rid of the slowdown effect though :(
    - Dave

  • Are this threads running concurrently?

    This is an example I reproduced from the Kathy&Bert's SCJP book.
    public class Machinery implements Runnable{
         Operator operator;
         public Machinery(Operator operator){
              this.operator = operator;
         public static void main(String[] args){
              Operator o = new Operator();
              Thread operator = new Thread(o);
              operator.setName("Operator");
              Machinery m = new Machinery(o);
              Thread machine = new Thread(m);          
              machine.setName("Machine");
              machine.start();
              operator.start();                    
         public void run(){     
              for(int c=0; c<2; ++c){
                   System.out.println("Machine...");
                   synchronized(operator){
                        try{
                             System.out.println("Machine waiting...");
                             operator.wait(5000);                         
                             for(int i=0; i<3; ++i){                    
                                  System.out.println("Machine processing...");
                                  Thread.sleep(2000);
                        }catch(InterruptedException ex){
                             ex.printStackTrace();
    class Operator implements Runnable{
         String name = Thread.currentThread().getName();
         public void run(){
              for(int c=0; c<2; ++c){
                   // Line 44...
                   System.out.println("Operator...");
                   synchronized(this){                    
                        try{
                        for(int i=0; i<3; ++i){                         
                             System.out.println("Operator operating...");
                             Thread.sleep(500);
                        notify();
                        wait(100);
                        }catch(InterruptedException ie){ie.printStackTrace();}
    }I don't know why after Operator notifies Machinery and get out of the synchronized code, the operator doesn't print the statement "Operator" on line 45 (there's a comment on line 44), I mean, this code is out of the synchronized block and since both threads are executing concurrently I thought it should print. I tried changing the Machinery's loop counter to 33 (to see if this was because of the scheduler "time slicing") so the "operator" line would print at least in between the machinery's loop print statements but I had no luck. Right now is as if both threads are running one at a time... I know I must be missing something here so if anyone can tell me what is I would really appreciate it.

    In your Operator class you do this.
    notify();
    wait(100);So it notifies machinery and then waits 100 milliseconds. The wait releases the lock allowing machinery to do its thing. The key thing to note is that Operator is still in the synchronized block of code.
    So basically, you don't see "Operator..." among the "Machine processing..." because the operator has to wait for Machinery to finish so that it may obtain the lock and exit the synchronized block.
    This is assuming the program is running as you wrote it. It's completely legal for the System.out statements to be moved into the synchronized blocks without your knowledge.

  • Concurrent request -one at a time

    I am going to run this request from PL/SQL,
    this is going to be called more than 1 time simultaniously, if more than 1 user runs the report at a time.
    I want to make it run one at a time, instead of running 2 different calls at same time.
    like i want to make the first request get completed and then run the next.
    How do i do it?
    FND_REQUEST.SUBMIT_REQUEST('BOM','BMCOIN','Import Bills and Routings',
                                                   NULL,FALSE,
                                              org_id,'1','1','1','1');

    Hi,
    Please see these threads.
    running cuncurrent request
    Re: running cuncurrent request
    Concurrent request compatibility Issue
    Concurrent request compatibility Issue
    Thanks,
    Hussein

  • Is it bad to have the fan running loud all the time

    the fan on my macbook runs loud and long at times. is this bad for the machine?

    Is it possible to have 2 threads running at the same
    time at different times eg 1 repeats every 20
    miliseconds and the other 40 for example. Yes.
    http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html

  • Why do I need to reflesh one, to two times just to view a webpage properly?

    Every time I visit a page, I have to refresh one, to two times before the page is able to be viewed properly. This happens on other computers, and other internet connections. How can I make it so the webpage is exactly as it should be the first time around? When I go to a page, I get the "basic" text version. Once I refresh, all the formatting, videos, and pictures will be up.

    import java.awt.;
    import javax.swing.;
    import java.awt.datatransfer.*;
    import java.io.FileReader;
    import java.io.IOException;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    public class Main extends JPanel implements MouseListener {
    public Main() {
    super(new GridLayout(2,2));
    final JTextArea jt= new JTextArea("dear test :) ",5,20);
    FileReader reader = null;
    System.err.println("Error closing reader");
    exception.printStackTrace();
    JButton bu = new JButton("copiar");
    final Clipboard clipboard = getToolkit().getSystemClipboard();
    //new add
    add(nn);
    add(tt);
    bu.addMouseListener(new MouseListener() {
    public void mouseEntered(MouseEvent e) {
    StringSelection data = new StringSelection(jt.getText());
    clipboard.setContents(data, data);
    public void mouseClicked(MouseEvent e) { }
    public void mousePressed(MouseEvent e) { }
    public void mouseReleased(MouseEvent e) {}
    public void mouseExited(MouseEvent e) { }
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("TextDemo");
    public static void main(String[] args) {
    //Schedule a job for the event dispatch thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    public void mouseClicked(MouseEvent e) { }
    public void mousePressed(MouseEvent e) { }
    public void mouseReleased(MouseEvent e) { }
    public void mouseEntered(MouseEvent e) { }
    public void mouseExited(MouseEvent e) { }
    } the problem is this line bu.addMouseListener(new MouseListener() {
    if i change this to bu.addMouseListener(this() {
    it gives error saying expected ')'
    and then doesn't compile.
    i just don't know why , although the program runs when i declare the methods two times,
    but i think it's better java code , if i learn it why is this error and correct it

  • Why the 'LIKE' operator takes so much time to run?

    I have a table T with 3 columns and 3 indexes:
    CREATE TABLE T
    id VARCHAR2(38) NOT NULL,
    fid VARCHAR2(38) NOT NULL,
    val NVARCHAR2(2000) NOT NULL
    ALTER TABLE T ADD (CONSTRAINT pk_t PRIMARY KEY (id,fid));
    CREATE INDEX t_fid ON T(fid);
    CREATE INDEX t_val ON T(val);
    Then I have the following two queries which differ in only one place - the 1st one uses the '=' operator whereas the 2nd uses 'LIKE'. Both queries have the identical execution plan and return one identical row. However, the 1st query takes almost 0 second to execute, and the 2nd one takes more than 12 seconds, on a pretty beefy machine. I had played with the target text, like placing '%' here and/or there, and observed the similar timing every time.
    So I am wondering what I should change to make the 'LIKE' operator run as fast as the '=' operator. I know CONTEXT/CATALOG index is a viable approach, but I am just trying to find out if there is a simpler alternative, such as a better use of the index t_val.
    1) Query with '=' operator
    SELECT id
    FROM T
    WHERE fid = '{999AE6E4-1ED9-459B-9BB0-45C913668C8C}'
    AND val = '3504038055275883124';
    2) Query with 'LIKE' operator
    SELECT id
    FROM T
    WHERE fid = '{999AE6E4-1ED9-459B-9BB0-45C913668C8C}'
    AND val LIKE '3504038055275883124';
    Execution Plan
    0 SELECT STATEMENT Optimizer=ALL_ROWS (Cost=1 Card=1 Bytes=99)
    1 0 TABLE ACCESS (BY INDEX ROWID) OF 'T' (Cost=1 Card=1 Bytes=99)
    2 1 INDEX (RANGE SCAN) OF 'T_VAL' (NON-UNIQUE) (Cost=4 Card=12)

    I will for sure try to change the order of the PK and see whether there will be any impact to the performance.
    In our application, val is much closer to a unique value than fid. In the example query, the execution plan showed that the index on val was indeed used in the execution of the query. That's why the 1st query took almost no time to return (our table T has more than 6 million rows).
    I was hoping the 'LIKE' operator would utilize the t_val index effectively and provide similar performance to the '=' operator. But apparently that's not the case, or needs some tricks.

  • How many threads can be running at the same time

    Hi!!
    Dows anyone knows how many Threads can be running at the same time in the JVM.
    I'm making a multi thread client-server app and I would like to know how much simultneous connections the JVM support. I'm using one Thread per connection.

    Hi, thanks to all for your answers.
    I think that I made the wrong question, as you said: "that means the number of threads currently created".
    I'm worry about this because my application is already online (It's a mail server -SMTP and POP3 server using ORACLE for the users database- ) and some other user post in the "multi-tread forum" that almost any JVM can only have 700 threads created at the same time, and I've never heard or read anything about this.
    what you mean with the stack space (memory??)
    I'm using the JavaWebServer 2.0 and a servlet to start the main Thread.
    Again Thanks to all for the answers but I think that the schapel answer is the one that solve my doubt...

  • Why won't Garage band let you open more than one project a time..

    Why won't Garageband let you open more than one project a time???? If thats the way its is set up...that is really lame. Even the worst audio programs allow you to run a few projects at a time.
    I recorded a gig the other night... then I dumped the whole set on to one track. When I wanted to copy and paste individual songs into their own project it made me close the current project. Is there a way around this???
    Joe

    Heh, heh. Yes, this is true. Alas... BUT, if you want to compare one project with another, it can be done.
    There is another advantage to making another copy of GarageBand. I created a copy and call it "GarageSymphony" that contains all my instrument specific icons for orchestral packs. This way I do not mess up the GarageBand application.
    I would not be surprised to find multiple windows become available in GB4. I was more than pleased to find this change in iMovie 6.

  • Thread run() resets value of variables! WHY!

    Hello.. i am having a VERY frustrating problem here. I have used a thread to create a stopwatch. I want to be able to play, pause and stop. I can get the play to start counitng, the stop to stop it...but..wheni pause...it pauses, yet when i resume the stopwatch, it starts again from 00:00:00:0
    II have four int variables.
    private int fractionOfSeconds;
    private int seconds;
    private int minutes;
    private int hours;
    in the constructor of the thread I am setting them to value 0;
    Stopwatch()
    fractionOfSeconds = 0;
    seconds = 0;
    minutes = 0;
    hours = 0;
    In the run() function I have it increment the values of those variables and pass the result to a label.
    public void run()
    isPlaying = true;
    isPaused = false;
    isStopped = false;
    try
    while(!isStopped && !isPaused)
    sleep(100);
    fractionOfSeconds++;
    if(fractionOfSeconds % 10 == 0 && fractionOfSeconds != 0)
    fractionOfSeconds -= 10;
    seconds++;
    if(seconds % 60 == 0 && seconds != 0)
    seconds -= 60;
    minutes++;
    if(minutes % 60 == 0 && minutes != 0)
    minutes -= 1;
    hours++;
    secondsString = "" + seconds;
    if(seconds < 10)
    secondsString = "0" + seconds;
    minutesString = "" + minutes;
    if(minutes < 10)
    minutesString = "0" + minutes;
    hoursString = "" + hours;
    if(hours < 10)
    hoursString = "0" + hours;
    transportControl.setTimerLabel(hoursString + ":" + minutesString + ":" + secondsString + ":" + fractionOfSeconds);
    catch(Exception e)
    LOGICALLY speaking..unless I am missing somehing really big, the stopwatch variables should be set to ZERO when the stopwatch class is contrsucted..and after that everytime i run the thread using the run() /start() function the variables should keep increasing..and every time i runit again it should keep counting from where it left off before.
    but it doenst. it resets the variables to zero EVERYTIME!!!
    Plese.anybody?what am i missing here??
    thanx in advance

    You can build a stop watch using one of the Timer classes.
    - Set the timer to tick every 55 milliseconds (18.2 Hertz) if your on an Intel based machine this is the best resolution you'll get.
    - When you start the stopwatch, record the currentMillis
    - when the timer ticks use that value and the currentMillis to determing the elapsed time.
    - when you pause the stopwatch shut the timer down and record the elapsed time so far
    - when you unpause the stopwatch restart the timer
    You probably don't even need a separate thread since the timer provide one for you. Note that times set in timers and sleep are not going to be the same as the time actually elapsed since these things run at very low priority.

  • Trying to figure out why is there a keystroke delay many times in Pages and Numbers? I'm on a 2010 macPro running Lion

    Trying to figure out why is there a keystroke delay many times in Pages and Numbers? I'm on a 2010 macPro running Lion

    I had a similar problem when working on a long Pages doc (40,000 words).The glitch only occurred on this one Pages file and affected no other applications. I fixed it by duplicating the file, trashing the original and working on the new document. I have no idea of the cause of the problem.

  • Can't get my threads to run at the same time  :-(

    Hi,
    I hope someone can help me. I have an two instances of an object that extends thread. In it's run method, there is a while loop that iterates while an int x (that starts at about 450) is not less than 0.
    In the while loop there is an x--; statement.
    Also inside the while loop is a call to yield();
    Also is a call sleep(5);
    Also in the while loop is a statement something like "System.out.println(x);"
    The int controls the vertical position of an icon (a JLabel) on the screen.
    In the class that has the main method, two instances of the thread object are created one after the other and run one after the other, although the program keeps running the first one until it has finished before running the second one!
    For example, the code looks something like this:-
    o1.run();
    System.out.println("o1 running");
    o2.run();
    System.out.println("o2 running");
    And the end printout (with the println call from the thread objects) looks like this:-
    o1 running
    450
    449
    448
    3
    2
    1
    o2 running
    450
    449
    etc.
    What's going on? Why won't it start running the second thread straight after the first one?
    Any help appreciated!

    class test extends Thread {
      private int i = 0;
      private String strMess = new String("");
      public static void main (String[] args)  {
         test t = new test("first");
         t = new test("second");
      test(String strIn){
           this.strMess = strIn;
           this.start();
      public void run(){
           while(i<5){
              System.out.println(this.strMess + i);
              try{this.sleep(200);}catch(Exception e){e.printStackTrace();}
              i++;
    }output:
    first0
    second0
    first1
    second1
    first2
    second2
    first3
    second3
    first4
    second4
    class test extends Thread {
      private int i = 0;
      private String strMess = new String("");
      public static void main (String[] args)  {
         test t = new test("first");
         t = new test("second");
      test(String strIn){
           this.strMess = strIn;
           this.run();
      public void run(){
           while(i<5){
              System.out.println(this.strMess + i);
              try{this.sleep(200);}catch(Exception e){e.printStackTrace();}
              i++;
    }output:
    first0
    first1
    first2
    first3
    first4
    second0
    second1
    second2
    second3
    second4

Maybe you are looking for