多线程
- Java中一次JVM启动,开启一个进程,进程享有全部资源
- 一个进程中包含多个线程,线程之间独立使用资源
- 线程属于宏观并行,微观串行,因为一个CPU
- 进程如果消失,那么所有的线程都会消失
- 线程资源,由JVM分配的CPU时间片,规定一个线程可以占用的时间,时间到,就要让出当前线程
java实现多线程的方法
- 继承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();
- 线程池Executors
以上两个方法为常规方案,每次执行线程任务,都会有创建线程和销毁线程的操作,这两个操作会耗费JVM的资源。
因此引入线程池概念,随用随取,并定义有几个存活线程。
3.1起始类Executors,创建线程池,并定义有几个存货线程
3.2使用Runnable方法,生成实例
3.3在线程池中,获取可用线程连接,执行任务
3.4完毕后,关闭线程连接,归还线程到线程池