注册 登录
编程论坛 JAVA论坛

关于多线程继承Runnable

渐渐鱼 发布于 2018-09-12 17:35, 1985 次点击
程序代码:
class Thread1 implements Runnable
{
    int i=10;
    public void run()
    {
        for(;i>0;)
        {
            System.out.printf("day"+"\n");
            i--;
        }
    }
}
class Thread2 implements Runnable
{
    int j=10;
    public void run()
    {
        for(;j>0;)
        {
            System.out.printf("night"+"\n");
            j--;
        }
        
        
    }
}
public class MyThread
{
    public static void main(String []args)
    {
        Thread1 day = new Thread1();
        Thread2 night = new Thread2();
        
        Thread thread1 , thread2;
        thread1 = new Thread(day);
        thread2 = new Thread(night);
        thread1.start();
        thread2.start();
        for(int k=0;k<10;k++)
        {
            System.out.printf("main thread..."+"\n");
        }
    }
}





Thread1 day = new Thread1();
        Thread2 night = new Thread2();
        
        Thread thread1 , thread2;
        thread1 = new Thread(day);
        thread2 = new Thread(night);
        thread1.start();
        thread2.start();

这一段不能直接调用而是thread1 = new Thread(day);样的,小白求教,不懂其中的原理????????
4 回复
#2
幻紫灵心2018-09-13 12:06

程序代码:

Thread1 thread1 =new Thread1(); //是new了一个Thread1的对象,这个对象不能直接start
Thread T = new Thread(thread1);//把thread1对象作为参数new一个Thread对象,这个才可以start
T.start();//Thread对象.start();
#3
渐渐鱼2018-09-14 09:51
回复 2楼 幻紫灵心
你的意思是Thread实例的对象才有start方法,所以不能直接调用,而如果是用了继承Thread这个类,就可以直接调用了?
#4
幻紫灵心2018-09-14 10:11
继承的可以直接start.
#5
渐渐鱼2018-09-14 15:05
回复 4楼 幻紫灵心
谢啦
1