thinkinjava
thinkinjava

Reputation: 95

Some problems about invoking the start() method in the Thread class

I am a beginer in the concurrency field,and today i do some exercises in the join() method. The code is :

public class ThreadJoinExample {
public static void main(String[] args) {
    Thread t1 = new Thread(new MyRunnable(), "t1");
    Thread t2 = new Thread(new MyRunnable(), "t2");
    Thread t3 = new Thread(new MyRunnable(), "t3");
    t1.start();
    try {
        t1.join(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    t2.start();
    try {
        t1.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    t3.start();
    try {
        t1.join();
        t2.join();
        t3.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}


class MyRunnable implements Runnable {

@Override
public void run() {
    System.out.println("Thread started:::"
            + Thread.currentThread().getName());
    try {
        Thread.sleep(4000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out
            .println("Thread ended:::" + Thread.currentThread().getName());
}

and the questinon,for example,when "t1.start()",i think the t1 will invoke the run() method immediately,but it not true;when "t1.join()",the t1 will invoke the run() method, i don not know the reason why causes it.My question are: 1. what happens when i invoke the start() method? 2. when thread t invoke the start() method,is the thread t will be pushed into the ready queue in the main memroy?

Upvotes: 0

Views: 76

Answers (2)

Sridhar DD
Sridhar DD

Reputation: 1980

  1. what happens when i invoke the start() method?

Calling start() tells the thread to create the necessary system resources and then execute the run() method asynchronously.

  1. when thread t invoke the start() method, is the thread t will be pushed into the ready queue in the main memory?

Yes. The start() method tells the Java Virtual Machine that it needs to create a system specific thread. After creating the system resource, it passes the Runnable object to it to execute its run() method.

Upvotes: 1

SMA
SMA

Reputation: 37023

1. what happens when i invoke the start() method?

When you invoke start method, it just gets ready to execute your thread. It may or may not be immediate and is dependent on when scheduler schedules your thread and then jvm will run your run method.

2. when thread t invoke the start() method,is the thread t will be pushed into the ready queue in the main memory?

Yes that's right. It may or may not start immediately executing your thread. You could try in main method starting your thread, it might happen that you main thread completed execution while your thread is yet to begin.

Upvotes: 1

Related Questions