1

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Rahul Baradia
  • 11,802
  • 17
  • 73
  • 121

2 Answers2

2

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.

Community
  • 1
  • 1
Azodious
  • 13,752
  • 1
  • 36
  • 71
1

You can't be sure about it nor you can do it.You call thread.start() to start a thread.But it depends on OS when it will be started.Even with setting priority you can't exactly achieve this.

Rasel
  • 15,499
  • 6
  • 40
  • 50
  • I am calling Thread_1.start() and Thread_1.start() simultaneously to run. But difference between both timing I want to remove it. – Rahul Baradia Dec 06 '12 at 12:15
  • You can't do this.Because OS defines when and how thread will be executed.You can pass your idea to os by setting priority that one has priority over other.But OS defines what it would do. – Rasel Dec 06 '12 at 12:17
  • ohk.. then there is no other way to do this ?? – Rahul Baradia Dec 06 '12 at 12:19