当前位置: 移动技术网 > IT编程>开发语言>Java > java多线程学习

java多线程学习

2019年03月26日  | 移动技术网IT编程  | 我要评论

什么是进程

进程是一个可执行的应用程序,任何进程都有一个主线程作为入口,是线程的集合

什么是多线程

多线程可以提高效率,我们在电脑操作的时候,开多个窗口,并不是多线程并发,是cpu在切换,只不过速度很快,我们感觉不到,多线程是在同一个时刻同时进行

为什么要使用多线程?

假设你有100桶水,你一个小时能打20桶,现在我们需要你一个小时内都把这些谁打完?怎么办?这时候需要多叫几个人一起打水

创建多线程的几种方式

1.继承thread类,实现run方法

2.匿名内部类

3.实现runable接口

4.callable

5.使用线程池创建

 

当我们启动多线程的时候,代码不是顺序执行,而是交替执行(异步,俩个线程互不印象),单线程是从上往下执行(同步)

继承thread

 

class threadtest extends thread{

    @override
    public void run() {
        for (int i=0;i<30;i++){
            system.out.println("run:"+i);
        }
    }
}
public class threaddemo {


    public static void main(string[] args) {

        threadtest t1 = new threadtest();
        t1.start();
        for (int i = 0; i <30 ; i++) {

            system.out.println("main:"+i);
            
        }
    }


}
thead

 实现runable接口

这方式比继承接口的方式要好用,因为java中是单继承,多实现的方式,你如果是继承了thread类就不能在继承别的类了

class threadtest02 implements runnable{

    @override
    public void run() {
        for (int i=0;i<30;i++){
            system.out.println("runable:"+i);
        }
    }
}

public class threaddemo02 {


    public static void main(string[] args) {

     new thread(new threadtest02()).start();
        for (int i = 0; i <30 ; i++) {

            system.out.println("main:"+i);
            
        }
    }


}
view code

匿名内部类的方式创建

     thread  t1  =   new thread(new runnable() {
            @override
            public void run() {
                for (int i = 0; i <10 ; i++) {
                    system.out.println("nei bu lei "+ i);
                }
            }
        });
     t1.start();
    }
view code

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网