Mohammed Lokhandwala
Mohammed Lokhandwala

Reputation: 49

Understanding Threads in java

I'm quite new to the concepts of threads in JAVA and though I tried a couple of codes and they are working I really don't exactly understand whats happening in the background. For example I wrote this piece of code:

public class myThreadTest implements Runnable {
  private static void ping(String text, int count) 
                      throws InterruptedException {
    for (int i = 0; i<count; i++) {
      System.out.println("ping "+text+i+"...");
      Thread.sleep(1000);
    }
  }
  public void run() {
    try {
      ping("run ",10);
    } catch (InterruptedException e) {
    }
  }  
  public static void main(String[] args) {
    (new Thread(new myThreadTest())).start();
    try {
      ping("main ", 5);
    } catch (InterruptedException e) {
    }
 }
}

are there 2 threads being executed here one running from main and the other from the method run? Bcoz the output I get is main,run,main,run,run,main... something like that.

Upvotes: 4

Views: 1753

Answers (4)

xagyg
xagyg

Reputation: 9721

There are two threads. One of the threads is created and starts executing its run method asynchronously due to the start call in the main block. The other thread is executing the main method itself.

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272417

That's correct. Try printing the thread id in your ping() method to see that different threads are running (you can also name your threads and I follow that as a practise so I can understand which thread is doing what)

Upvotes: 2

JohnnyQ
JohnnyQ

Reputation: 543

Threads in java have mainly to do with concurrency, which is s the notion of multiple things happening at the same time.A thread is an independent path of execution within a program.

From your program I can see your code is starting two threads at start up running the first command the for loop sleeping for 1 second then and then running run method and back and forth until the for loop is exhausted so the run continues to 9

Upvotes: 2

Suresh Atta
Suresh Atta

Reputation: 122026

Yes ,the both executing concurrently.

A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.

I am highly recommending this docs before starts coding .good luck

Upvotes: 3

Related Questions