Reputation: 449
class Callme {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
public void run() {
//synchronized(target){ // synchronized block
target.call(msg);
//}
}
}
class Synch {
public static void main(String args[]) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
ob1.t.setPriority(Thread.NORM_PRIORITY);
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
ob2.t.setPriority(Thread.MAX_PRIORITY);
ob3.t.setPriority(Thread.MIN_PRIORITY);
System.out.println(ob1.t.getPriority());
System.out.println(ob2.t.getPriority());
System.out.println(ob3.t.getPriority());
// wait for threads to end
try {
ob1.t.wait();
ob2.t.wait();
ob3.t.wait();
ob1.t.notifyAll();
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
}
}
Whereas we give priority to child threads and wait()
and notifyall()
methods are used so have to run according to priority. But not run. If we use synchronized(target)
also, then also not run according to priority.
Upvotes: 1
Views: 1196
Reputation: 28762
The Tread.setPriority()
changes the execution priority of the thread, which means that a higher priority thread has a better chance of getting picked for execution when running (compared to a concurrently running lower priority thread). Of course, if you stop the thread with excplicit call to wait()
, it will not be running while waiting, so the priority is meaningless in that situation.
Update: as mentioned above the priority is for running threads. When you call notify()
the thread selected is not based on priority (at least it is not guaranteed to, the specification does not say one way or another)
Upvotes: 3
Reputation: 200148
Java Language Specification, 17.2.2 Notification:
"There is no guarantee about which thread in the wait set is selected."
Take note of the carefully chosen terminology: a wait set.
Upvotes: 1
Reputation: 39897
It depends on the operating system the program is running on. Few operating system doesn't heed about the priority set by application -- or behave unexpectedly. Hence, one should not depend on priority.
Similar thread found:
Thread priority and Thread accuracy
Upvotes: 1