1、为什么用runable接口
对于java来说不能实现多继承,所以说,对于一个类来说,如果有自己的父类,但是还要想继承线程(thread类)类的话,就出现问题啦。
2、实现runable接口,此接口就有一个方法,run()。此run()方法用于执行线程任务。
class Demohehe implements Runnable //但是Demohehe不是线程对象
所以,还要创建线程对象.
在thread的构造函数中,有一个是带有runable接口的构造函数。
Thread(Runnable target)
分配新的 Thread
对象。
Demohehe t1 = new Demohehe();
Thread nt1 = new Thread(t1);
Thread nt2 = new Thread(t1);
nt1.start();
nt2.start();
3、代码
package com.xiancheng;
class Demohehe implements Runnable
{
public void run()
{
for(int x=0;x<=10;x++)
{
for(int y=0;y<=99999999;y++){}
System.out.println(Thread.currentThread().getName()+"....x="+x);
}
}
}
public class hello {
public static void main(String[] args){
Demohehe t1 = new Demohehe();
Thread nt1 = new Thread(t1);
Thread nt2 = new Thread(t1);
nt1.start();
nt2.start();
}
}