请教大家一个JAVA中的接口问题,在下面的程序里如果不实现Runnable接口,而是直接在类A中添加一个run()那么编绎时会出错。
可是Runnable接口中也就一个run()方法,我自己在类A中加一个run()就不行了吗?
加implements Runnable与不加implements Runnable 它们实现的机制有什么不一样呢?class A implements Runnable //如果去掉implements Runnable,那么编绎时会出错。
{
public void run()
{
System.out.println("hello I'm A");
}
}public class Test
{
public static void main(String args[])
{
A a =new A();
new Thread(a).start();
}
}
可是Runnable接口中也就一个run()方法,我自己在类A中加一个run()就不行了吗?
加implements Runnable与不加implements Runnable 它们实现的机制有什么不一样呢?class A implements Runnable //如果去掉implements Runnable,那么编绎时会出错。
{
public void run()
{
System.out.println("hello I'm A");
}
}public class Test
{
public static void main(String args[])
{
A a =new A();
new Thread(a).start();
}
}
只有这样你在调用run()方法时才不会出错,因为在new Thread(a).start();中是指定了要去实现Runnable借口的
既然你没有去重写它的run()方法,那就肯定是要报错的拉!
"因为在new Thread(a).start();中是指定了要去实现Runnable借口的"new Thread(a).start(); 这句是怎么指定要实现Runnable接口的?
1 继承 extends Thread
2 实现 implements Runnable并且要重写 run()方法... 除非你不想实现多线程
我知道这两种方法, 我的疑问是对于第二种方法 "实现implements Runnable " 为什么一定要implements Runnable呢,加入run()方法不就好了吗?
你44用线程对象调用 start();
和run(); 方法运行一下 start()是启动线程
run()是调用方法
你实现implements Runnable 就是线程
没实现的就是方法
我知道这两种方法, 我的疑问是对于第二种方法 "实现implements Runnable " 为什么一定要implements Runnable呢,加入run()方法不就好了吗?
-------------------------------
实现了Runnable接口的类还不算线程,因为接口只是提供空函数,并不作什么特别的处理,所以这样的类只能说是可能成为线程,还必须用Thread(Runnable target)构造函数生成一个线程对象并启动才算是线程
你自己写一个类带有run方法可以,但是该类不能通过Thread构造函数生成线程对象就不能成为线程,所以结论就是还是要实现Runnable
---------------------
没有什么特别的,就是我上面说的,关键是Thread的构造函数需要的是Runnable接口而不是你要的类
SUN公司的规定每种语言都有自己的格式和规定你想得到回报必须付出
你想实现多线程就要实现Runnable借口,或者继承Thread
Thread的构造函数是怎么判断你是否实现了Runnable接口呢?
·去掉所说的应该是这里出错应该是类Thread这里调用的接口的东西
public void start()
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method). It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
Throws:
IllegalThreadStateException - if the thread was already started.
See Also:
run(), stop()
调用start方法将使该线程开始运行,java虚拟机将调用该线程的run方法
结果是2个线程将并行执行。
不要重复执行一个线程的start方法。你指的是想看start方法的源代码??那你直接看源代码。sun可以下载的。
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
group.add(this);
start0();
if (stopBeforeStart) {
stop0(throwableFromStop);
}
}
这个是thread类里面start()的源代码。
里面有所有的源代码的