多线程编程入门

1.线程

  • 线程被称为“轻量级进程”
  • 每个线程对应一个独立的执行流
  • 一个进程包含了多个线程,线程共享进程的资源
  • 进程有独立性
  • 线程如果出了问题,可能会影响进程。
  • 创建线程的开销比创建进程小
  • 进程是系统分配资源的最小单位,线程是系统调度的最小单位。一个进程内的线程之间是可以共享资源的。

2.进程和线程的区别

  • 1.进程包含线程,一个进程可以包含一个进程,也可以包含多个线程
  • 2.进程是资源分配的基本单位,线程是系统调度执行的基本单位。
  • 3.进程和进程之间是相互独立的,同一个进程的若干线程之间,共享一些资源,如果某个线程出现异常,可能会导致整个进程终止,因此,其他线程也无法工作了。

3.新建线程

  • 1.创建一个类,继承自Thread
  • 2.重写run方法,写入线程要执行的代码
  • 3.创建子类实例
  • 4.调用子类Start方法
/**
 * User:yang
 */

class MyThread extends Thread{
    @Override
    public void run() {
        //线程要执行的代码
        while (true){
            System.out.println("这是新线程");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


public class Test {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("hello world");
        MyThread myThread=new MyThread();
        myThread.start();
        while(true){
            System.out.println("这是主线程");

            Thread.sleep(1000);

        }
    }
}

4.多线程

/**
 * User:yang
 */
public class ThreadDemo1 {
    private static long count = 100_0000_0000L;

    public static void serial() {
        //执行速度慢
        //计时
        long start = System.currentTimeMillis();
        long a = 0;
        for (long i = 0; i < count; i++) {
            a++;
        }
        long b = 0;
        for (long i = 0; i < count; i++) {
            b++;
        }
        long end = System.currentTimeMillis();
        System.out.println("执行时间" + (end - start));
    }

    public static void concurrency() throws InterruptedException {
        //concurrency并发的意思
        long start=System.currentTimeMillis();
        Thread t1=new Thread(){
            //匿名内部类

            @Override
            public void run() {
                long a=0;
                for (long i = 0; i <count ; i++) {
                    a++;
                }
            }
        };
        t1.start();

        Thread t2=new Thread(){
            @Override
            public void run() {
                long b=0;
                for (long i = 0; i <count ; i++) {
                    b++;
                }
            }
        };
        t2.start();
        t1.join();
        t2.join();
        long end=System.currentTimeMillis();
        System.out.println("执行时间"+(end-start));
    }

    public static void main(String[] args) throws InterruptedException {
//        serial();
        concurrency();

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值