当前位置: 移动技术网 > IT编程>开发语言>Java > 实现多线程的两种传统方式

实现多线程的两种传统方式

2018年10月18日  | 移动技术网IT编程  | 我要评论

总裁来袭豪门联姻,尖锐湿疣图片,龙腾天朝

第一种:创建一个类继承thread类,重写thread类的run方法,代码如下:

class thread1 extends thread {
    @override
    public void run() {
        while (true) {
            try {
                thread.sleep(1000);// 线程睡眠1s
            } catch (interruptedexception e) {
                // todo auto-generated catch block
                e.printstacktrace();
            }
            system.out.println(thread.currentthread().getname());// 打印当前线程名称
        }
    }
}

public class test {

    public static void main(string[] args) {

        thread1 thread1 = new thread1();
        thread1.start();//启动线程
    }

}

 

第二种方式:创建一个类实现runable接口,重写runable接口的run方法,并将该类的对象作为参数传递给thread类的有参构造方法,代码如下:

class thread2 implements runnable{

    @override
    public void run() {
        while (true) {
            try {
                thread.sleep(1000);// 线程睡眠1s
            } catch (interruptedexception e) {
                // todo auto-generated catch block
                e.printstacktrace();
            }
            system.out.println(thread.currentthread().getname());// 打印当前线程名称
        
    }}
}

public class test {

    public static void main(string[] args) {

        thread thread = new thread(new thread2());
        thread.start();//启动线程
    }
}

 

两种方式的区别:如果一个类继承thread,则不适合资源共享。但是如果实现了runable接口的话,则很容易的实现资源共享。

实现runnable接口比继承thread类所具有的优势:

1):适合多个相同的程序代码的线程去处理同一个资源

2):可以避免java中的单继承的限制

3):增加程序的健壮性,代码可以被多个线程共享,代码和数据独立

注意:main方法其实也是一个线程。在java中所有的线程都是同时启动的,至于什么时候,哪个先执行,完全看谁先得到cpu的资源。

java中,每次程序运行至少启动2个线程。一个是main线程,一个是垃圾收集线程。因为每当使用java命令执行一个类的时候,实际上都会启动一个jvm,每一个jvm实际上就是在操作系统中启动了一个进程。

 

     

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网