Reputation: 461
Q:I need a detailed explanation on the outputs of the following codes... What is the difference for the thread created using runnable interface and the thread created directly by extending thread class...???
Q1:
public class BalanceChecker1{
public static void main(String [] args) {
RunnableClass runnableClass=new RunnableClass();
new Thread(runnableClass).start();
new Thread(runnableClass).start();
}
}
class RunnableClass implements Runnable{
Bean bean=new Bean();
public void run(){
synchronized(bean){
bean.incBalance();
}
}
}
class Bean{
private int balance=0;
public void incBalance(){
balance++;
System.out.println(" The thread name "+Thread.currentThread().getName());
System.out.println(" The balance is "+balance);
}
}
OUTPUT:
The thread name Thread-0 The balance is 1 The thread name Thread-1 The balance is 2
Q2:
public class BalanceChecker1{
public static void main(String [] args){
new specialThread().start();
new specialThread().start();
}
}
class specialThread extends Thread{
Bean bean=new Bean();
public void run(){
synchronized(bean){
bean.incBalance();
}
}
}
class Bean{
private int balance=0;
public void incBalance(){
balance++;
System.out.println(" The thread name "+Thread.currentThread().getName());
System.out.println(" The balance is "+balance);
}
}
OUTPUT:
The thread name Thread-0 The thread name Thread-1 The balance is 1 The balance is 1
Upvotes: 1
Views: 224
Reputation: 308209
The important difference between those two examples is not in Runnable
vs. extending Thread
(on an unrelated note: there's almost never a reason to extend Thread
, you almost always want to implement Runnable
.
The important difference is that in the first example both running threads share a common Bean
object on which they synchronize! This means that the call to incBalance()
can't be executed by both threads at once.
In the second example they have a separate Bean
object each, so the synchronization has no practical effect.
Also note that the output you posted is not guaranteed: you could get the same output in the second example as in the first (you can't get the mixed output from the second example form the first, however).
Upvotes: 6