47

Could anyone give an example program that explains Java Threads in a simple way? For example, say I have three threads t1, t2 and t3. I want a code that demonstrates that the threads execute simultaneously, and not sequentially.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
JavaUser
  • 25,542
  • 46
  • 113
  • 139
  • 3
    So what exactly is your question? Right now it just sounds like "give me code" and we don't do that... not to mention, even in that case I'm not sure exactly what this code you seem to want is supposed to do. – David Z Mar 28 '10 at 05:00
  • 1
    Just to understand concurrent programming by practical example David . – JavaUser Mar 28 '10 at 05:12
  • I took your question to mean you wanted an example to prove that threads do what they say they'll do, visually. I hope my answer helps, despite the output of each thread being anything but practical. – Phil Mar 28 '10 at 05:22
  • I always liked this [example][1] that lets multiple threads share the console. [1]:http://groups.google.com/group/comp.lang.java.programmer/msg/5f02abeda114d88e – trashgod Mar 28 '10 at 05:04
  • [have look](http://www.codeproject.com/Articles/616115/Java-Thread-Example) –  Jul 11 '13 at 21:48

4 Answers4

77

Here is a simple example:

ThreadTest.java

public class ThreadTest
{
   public static void main(String [] args)
   {
      MyThread t1 = new MyThread(0, 3, 300);
      MyThread t2 = new MyThread(1, 3, 300);
      MyThread t3 = new MyThread(2, 3, 300);

      t1.start();
      t2.start();
      t3.start();
   }
}

MyThread.java

public class MyThread extends Thread
{
   private int startIdx, nThreads, maxIdx;

   public MyThread(int s, int n, int m)
   {
      this.startIdx = s;
      this.nThreads = n;
      this.maxIdx = m;
   }

   @Override
   public void run()
   {
      for(int i = this.startIdx; i < this.maxIdx; i += this.nThreads)
      {
         System.out.println("[ID " + this.getId() + "] " + i);
      }
   }
}

And some output:

[ID 9] 1
[ID 10] 2
[ID 8] 0
[ID 10] 5
[ID 9] 4
[ID 10] 8
[ID 8] 3
[ID 10] 11
[ID 10] 14
[ID 10] 17
[ID 10] 20
[ID 10] 23

An explanation - Each MyThread object tries to print numbers from 0 to 300, but they are only responsible for certain regions of that range. I chose to split it by indices, with each thread jumping ahead by the number of threads total. So t1 does index 0, 3, 6, 9, etc.

Now, without IO, trivial calculations like this can still look like threads are executing sequentially, which is why I just showed the first part of the output. On my computer, after this output thread with ID 10 finishes all at once, followed by 9, then 8. If you put in a wait or a yield, you can see it better:

MyThread.java

System.out.println("[ID " + this.getId() + "] " + i);
Thread.yield();

And the output:

[ID 8] 0
[ID 9] 1
[ID 10] 2
[ID 8] 3
[ID 9] 4
[ID 8] 6
[ID 10] 5
[ID 9] 7

Now you can see each thread executing, giving up control early, and the next executing.

Phil
  • 2,828
  • 1
  • 23
  • 20
8

There is no guarantee that your threads are executing simultaneously regardless of any trivial example anyone else posts. If your OS only gives the java process one processor to work on, your java threads will still be scheduled for each time slice in a round robin fashion. Meaning, no two will ever be executing simultaneously, but the work they do will be interleaved. You can use monitoring tools like Java's Visual VM (standard in the JDK) to observe the threads executing in a Java process.

Tim Bender
  • 20,112
  • 2
  • 49
  • 58
  • 1
    Tim, it seems that it's a real question. The OP said he just wanted a practical example (sure the OP could google it, but it's not necessarily an invalid question). – Kiril Mar 28 '10 at 15:53
  • 4
    I think what I meant is that it isn't really a question in the sense that it doesn't fit a Q&A format. Instead it asks for sample code. Regardless, it was abrasive so I edited my answer, which is still technically correct. There is no way to definitively demonstrate simultaneous execution. Even the accepted answer only demonstrates interleaving. – Tim Bender Aug 10 '12 at 20:25
4

A simple example:

public class Test extends Thread {
    public synchronized void run() {
        for (int i = 0; i <= 10; i++) {
            System.out.println("i::"+i);
        }
    }

    public static void main(String[] args) {
        Test obj = new Test();

        Thread t1 = new Thread(obj);
        Thread t2 = new Thread(obj);
        Thread t3 = new Thread(obj);

        t1.start();
        t2.start();
        t3.start();
    }
}
ProgramFOX
  • 6,131
  • 11
  • 45
  • 51
Sahil Jain
  • 41
  • 1
0

create java application in which you define two threads namely t1 and t2, thread t1 will generate random number 0 and 1 (simulate toss a coin ). 0 means head and one means tail. the other thread t2 will do the same t1 and t2 will repeat this loop 100 times and finally your application should determine how many times t1 guesses the number generated by t2 and then display the score. for example if thread t1 guesses 20 number out of 100 then the score of t1 is 20/100 =0.2 if t1 guesses 100 numbers then it gets score 1 and so on