一、从底层源码:
1、Thread是一个实现Runable接口的的类,Runable是一个接口。
class Thread implements Runnable {
/* Make sure registerNatives is the first thing <clinit> does. */
private static native void registerNatives();
static {
registerNatives();
}
public
interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
可以看出Thread实现接口中的run方法,并构造了自己的方法,Runable 接口只有一个方法,即run();
2、其中两个钟都有run()方法和Start()方法
run()方法启动两个线程时,一个线程结束之后,才执行另一个线程,没有交互执行;start方法,可以交互执行,其实启动start方法,其实在jvm中会找run()方法。
3、启动来说
Thread 启动new Thread().start();Runable 中启动得靠Thread类中的方法
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
进行启动。
二、代码实现分析:
public class TestRunableAndThread {
public static void main(String[] args){
myTest m1 = new myTest();
new Thread(m1).start();//Runable启动两个线程消耗100次
new Thread(m1).start();//
new myTe().start();//Thread 是创建两个线程对象,每个对象消耗100次
new myTe().start();
}
}
class myTe extends Thread{
int t=100;
public void run() {
while(true){
if(t>0){
System.out.println(Thread.currentThread().getName() +
" is saling ticket " +t--);
}
else{
break;
}
}
}
}
class myTest implements Runnable{
int t=100;
@Override
public void run() {
while(true){
if(t>0){
System.out.println(Thread.currentThread().getName() +
" is saling ticket runrunrurn " +t--);
}
else{
break;
}
}
}
}
创建线程的启动,以及启动线程的个数,消耗的次数都有很大的区别。
6819

被折叠的 条评论
为什么被折叠?



