[英]Unexpected difference in behaviour between using a thread using a Runnable and a derived Thread class
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: 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: 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
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
. 这两个示例之间的重要区别不在
Runnable
与扩展Thread
(不相关的注:几乎没有理由扩展Thread
,而您几乎总是想实现Runnable
。
The important difference is that in the first example both running threads share a common Bean
object on which they synchronize! 重要的区别在于,在第一个示例中,两个正在运行的线程共享一个公共
Bean
对象,并在该对象上进行同步! This means that the call to incBalance()
can't be executed by both threads at once. 这意味着两个线程不能一次执行对
incBalance()
的调用。
In the second example they have a separate Bean
object each, so the synchronization has no practical effect. 在第二个示例中,它们每个都有一个单独的
Bean
对象,因此同步没有实际效果。
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). 还要注意,不能保证您发布的输出是保证的:第二个示例中的输出与第一个示例中的输出相同(但是,第二个示例中的混合输出无法从第一个示例中获得)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.