Skip to content
Advertisement

Run multi-thread at a time and make thread to run fast

I am trying to run two different threads at a time, but unable to do that. Thread_1 & Thread_2 runs, but difference between them is around 500ms. I am not using wait() or sleep() anywhere in my code.

Questions:

  1. How to make run thread simultaneously or in parallel?

  2. How to make thread run fast?

For second question this I used Thread.setPriority(Thread.MAX_PRIORITY) but time difference between other is same.

Updated with example code

Doing same as below example, but takes more time between both threads to run.

public static void main(String args[])
{
    MyThread thread1 = new MyThread("thread1: ");
    MyThread thread2 = new MyThread("thread2: ");
    thread1.start();
    thread2.start();
    boolean thread1IsAlive = true;
    boolean thread2IsAlive = true;
    do {
       if (thread1IsAlive && !thread1.isAlive()) {
           thread1IsAlive = false;
            System.out.println("Thread 1 is dead.");
       }
       if (thread2IsAlive && !thread2.isAlive()) {
           thread2IsAlive = false;
           System.out.println("Thread 2 is dead.");
       }
    } while(thread1IsAlive || thread2IsAlive);
}

I have searched the web and gone through some docs. What can I try next?

Advertisement

Answer

How to make run thread simultaneously or in parallel?

As a programmer it’s only possible on multi processor machines. On single processor only one thread will run at one time and it’s upto JVM (and OS) to choose which thread to run.

How to make thread run fast ?

You can try (as you did), but overall control is with JVM (and OS) only.

However, increasing the priority of thread doesn’t mean that it’ll run fast. it only makes chances for the thread to run more frequently than other threads. i.e. OS may (or may not)choose it more no. of times than other threads.

Go through this link for some more details. Check this too.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement