简体   繁体   中英

I am trying to call thread 2 from thread 1 (for five times in a loop), but thread 2 starts executing only after the loop in thread 1 is complete

I have a 2 threads defined in an android activity. Both threads are created as runnable instances. Thread 1 is a runnable object called "timer1" (created using an anonymous inner class) and Thread 2(assigned to runnable object "timer2") is invoked from Thread 1 using Thread 2's handler (using the post() method).

Thread 2's handler is called "tempHandler" (it is an instance variable) and is initialized in the constructor of the "MyRunnable" class.

Thread1 makes 5 calls to Thread2 in a for loop. The intended outcome is that Thread2 should run each time a post() call is made to it. But it does not happen. Instead the entire loop in Thread1 completes and only then does Thread2 run. Why does this happen? And how to rectify it?

This is the 1st thread:

timer1 = new Runnable() {
        @Override
        public void run() {
            timer2 = new MyRunnable();

            for(int i = 0; i < 5; i++){
                tempHandler.post(timer2);
                try{
                    Thread.sleep(1000);
                } catch(Exception e) {
                    System.out.println(e.getMessage());
                }
            }

        }
    };

This is the 2nd thread:

public class MyRunnable implements Runnable {

    public MyRunnable() {
        tempHandler = new Handler();
    }

    @Override
    public void run() {
        if(Looper.myLooper() == null) {
            Looper.prepare();
        }
        long startTime = System.currentTimeMillis();
        long stopTime = System.currentTimeMillis();
        long elapsedTime = stopTime - startTime;

        System.out.println("Array traversal time: " + String.valueOf(elapsedTime));
        System.out.println("Exited thread 2");

        Looper.loop();
    }
}

You haven't shown the code that starts the threads, but it sounds like maybe you're assuming Runnable s are Thread s. They're not.

A Runnable is just that: a thing you can run by calling its run() method. But it runs in the same thread you call it from.

An example to see what I'm talking about:

public static void main(String[] args) {
    final Thread mainThread = Thread.currentThread();
    Runnable r = new Runnable() {
        @Override
        public void run() {
            System.out.println(mainThread);
            System.out.println(Thread.currentThread());
            System.out.println(mainThread == Thread.currentThread());
        }
    };
    r.run();
}

The output is something like:

Thread[main,5,main]
Thread[main,5,main]
true

You create a separate thread which will run the Runnable by calling new Thread(r) . Replacing the line r.run(); in the above example with:

    Thread newThread = new Thread(r);
    newThread.start();

The output becomes:

Thread[main,5,]
Thread[Thread-0,5,main]
false

Success – we have two different threads!

Note: make certain you are calling start() on your Thread objects, and not run() . That's the other possible reason your code isn't working. Although Thread objects have a public run() method, this is a historical mistake in Java; you should never call it , because that just runs the code on the current thread without starting a new one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM