2012-10-25 74 views

回答

6

这些是不同的实例相同类型,绝对不一样的线程,你可以这样做。

这个符号可以使它更清楚为什么(虽然它是相当于从输出线分开原件):

Thread instance1 = new MyThread(0); //created one instance 
Thread instance2 = new MyThread(1); //created another instance 

//we have two different instances now 
// let's see if that is true, or not: 
System.out.println("The two threads are " + (instance1==instance2?"the same":"different")); 

instance1.start(); //start first thread instance 
instance2.start(); //start second instance 

//we just started the two different threads 

不过,根据MyThread实施,这威力带来问题。多线程编程并非易事。线程实例应该以线程安全的方式运行,这对保证并不重要。

推荐阅读:Java Concurrency In Practice (Peierls, Bloch, Bowbeer, Holmes, Lea)

+1

打我回答:) –

+0

只需几秒钟...人们围绕着Java主题快速... – ppeterka

+0

@ppeterka大多数时间它*低挂果*。很多代表很少费力。 – maba

1

是的,因为你实例化两个线程。

尽管它们具有相同的类(MyThread),但每次在java中使用new关键字时,都会实例化一个新对象。这个新对象不能与原始对象共享数据。您已创建两个单独的MyThread对象;你可以启动一个而不是另一个,或者启动两者。

+0

你的意思是他们不是一回事? –

3

由于the documentation说,你不能多次启动一个线程 - 如果你在已经启动的线程上调用start(),你会得到一个IllegalThreadStateException

但是,你的代码不会做你说:你是不是开始同一线程两次与代码 - 你创建你启动两个独立的MyThread对象。

相关问题