Setting a threads priority can be very useful if one thread has more critical tasks to perform than another. The Thread class has a method called setPriority(int level) with which you can alter the priority a Thread instance has. The priority level range from 1 (least important) to 10 (most important) and if no level is explicitly set, a Thread instance has the priority level of 5. In the first example below no priorites are set, so both threads have the priority level 5. The TestThread class implements the Runnable interface and in its run() method loops from 1 to 10 and output the number along with its Thread id, which is passed to the constructor.
public class Main { public void setPrioritiesOnThreads() { Thread thread1 = new Thread(new TestThread(1)); Thread thread2 = new Thread(new TestThread(2)); thread1.start(); thread2.start(); try { thread1.join(); thread2.join(); } catch (InterruptedException ex) { ex.printStackTrace(); } System.out.println("Done."); } public static void main(String[] args) { new Main().setPrioritiesOnThreads(); } class TestThread implements Runnable { int id; public TestThread(int id) { this.id = id; } public void run() { for (int i = 1; i <= 10; i++) { System.out.println("Thread" + id + ": " + i); } } } }
If you need any urgent assistance on Setting_thread_priorities, kindly email your requirement to us at : info@javagenious.com or Contact-an-Expert. Our experts will try their best to solve your problem.
Keyword Tags: Setting_thread_priorities tutorial,Setting_thread_priorities in java,Concepts of Setting_thread_priorities,Java,J2EE,Interview Questions,Setting_thread_priorities Examples
Most programming languages compile source code directly into machine code, suitable for execution on a particular microprocessor architecture. read more
|