4

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.

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2

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)

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.