多线程简介

多线程

  1. Java中一次JVM启动,开启一个进程,进程享有全部资源
  2. 一个进程中包含多个线程,线程之间独立使用资源
  3. 线程属于宏观并行,微观串行,因为一个CPU
  4. 进程如果消失,那么所有的线程都会消失
  5. 线程资源,由JVM分配的CPU时间片,规定一个线程可以占用的时间,时间到,就要让出当前线程

java实现多线程的方法

  1. 继承Thread类
    1.1编写一个普通类继承Thread类,覆盖run()方法
public class Thread1 extends Thread{
 @Override
 public void run() {
  for(int i = 0 ; i < 5 ; i++) {
   System.out.println(i+"thread1 is working");
   try {
    Thread.sleep(1000);
    System.out.println(Thread.currentThread().getName());
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
 }
}
 1.2生成Thread对象,调用start()方法,执行任务
 public static void main(String[] args) {
  Store store = new Store();
  Thread1 thread1 = new Thread1();
  thread1.start();

2.实现Runnable接口(避免单继承限制)
2.1编写一个普通类,实现Runnable接口,覆盖run()方法

public class Runnable1 implements Runnable{
 
 @Override
 public void run() {
  for(int i=0;i<5;i++) {
   System.out.println(i+"Runnable1 is working!");
   try {
    Thread.sleep(1000);
    System.out.println(Thread.currentThread().getName());
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
}
public class Runnable2 implements Runnable{
 
 @Override
 public void run() {
  for (int i = 0; i < 5; i++) {
   System.out.println(i+"Runnable2 is working!");
   try {
    Thread.sleep(1000);
    System.out.println(Thread.currentThread().getName());;
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
}

 public static void main(String[] args) {
  Store store = new Store();
  Runnable1 runnable1 = new Runnable1();
  Runnable2 runnable2 = new Runnable2();
  Thread tr1 = new Thread(runnable1);
  Thread tr2 = new Thread(runnable2);
  tr1.start();
  tr2.start();
  1. 线程池Executors
    以上两个方法为常规方案,每次执行线程任务,都会有创建线程和销毁线程的操作,这两个操作会耗费JVM的资源。
    因此引入线程池概念,随用随取,并定义有几个存活线程。
    3.1起始类Executors,创建线程池,并定义有几个存货线程
    3.2使用Runnable方法,生成实例
    3.3在线程池中,获取可用线程连接,执行任务
    3.4完毕后,关闭线程连接,归还线程到线程池
多线程图解

多线程图解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值