Java Process与Thread

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java Process与Thread

留在梦里   2022-06-03 我要评论

进程和线程的关系

⭐在操作系统中运行的程序就是进程,比如说QQ,播放器,游戏等等…程序是指令和数据的有序集合,其本身没有任何运行的含义,是一个静态的概念.

⭐进程和线程都是为了处理并发编程这样的场景,但是进程有问题,频繁拆功创建和释放资源的时候效率低,相比之下,线程更轻量,创建和释放效率更高.

⭐进程具有独立性,每个进程有各自独立的虚拟地址空间,一个进程挂了,不会影响其他进程,同一个进程中的多个线程,共用同一个内存空间,一个线程挂了,可能影响其他的线程,甚至导致整个进程崩溃…

⭐而进程则是执行程序的一次执行过程,他是一个动态的概念,是系统资源分配的单位

⭐通常在一个进程中可以包含多个线程(如果把进程想象成一个工厂,那么线程就是工厂里的生产线,一个工厂里面面可以有一个生产线,也可以有多个生产线),当然一个进程中至少一个线程,不然没有存在的意义,线程是CPU调度和执行的单位.

⭐真正的多线程是指有多个CPU,即多核.

⭐线程就是独立执行的路径

⭐在程序执行时,即使没有自己创建线程,后台也会有多个线程,如主线程,GC线程.

⭐每个线程在自己的工作内存交互,内存操控不当会造成数据不一致.

操作系统是如何管理进程的

1.先描述一个进程.(明确除一个进程上面的一些相关属性)

2.在组织若干个进程.(使用一些数据结构,把很多描述进程的信息放到一起,方便进行增删查改,典型的实现,就是使用双向链表把每个进程的PCB串起来).

并行和并发

并行:微观上,两个CPU核心,同步你是执行两个任务的代码.

并发:微观上,一个CPU核心,先执行一会任务1,在执行一会任务2,在执行一会儿任务3,只要切换足够快,宏观上看起来,就好像很多任务同时执行一样,

并发和并行,只有在微观上可以区分,宏观上区分不了,微观上这里的区分都是都是操作西欧统自动调度的结果.正因为供观赏区分不了并行和并发,在写代码的时候不去区分,只是在研究操作系统进程调度的时候稍做区分,其它场景基本都是使用并发作为一个统称来代替.

创建线程的方法

方法一: 通过Thread类创建线程,这是最简单的方法,创建子类,继承Thread类,并重写run方法.

package thread;
class MyThread extends Thread{
    @Override
    public void run() {
        System.out.println("hello thread");
    }
}
public class Demo1 {
    public static void main(String[] args) {
        Thread t = new MyThread();
        t.start();
    }
}

方法二:

import java.util.Scanner;

class MyThread2 extends Thread{
    @Override
    public void run() {
        System.out.println("hello thread!");
        try {
            Thread.sleep(1000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}
public class Demo2 {
    public static void main1(String[] args) {
        Thread t = new MyThread2();
        t.start();
        while (true) {
            System.out.println("hello main!");
            try {
                Thread.sleep(1000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }

方法三: 创建一个匿名内部类,继承自Thread类,同时重写run方法,同时再new出这个匿名内部类的实例.

import java.util.*;
class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("hello!");
    }
}
public class Demo3 {
    public static void main1(String[] args) {
        Thread t = new Thread(new MyRunnable());
        t.start();
    }

方法四: 同样使用了匿名内部类.

public class Demo4 {
    public static void main(String[] args) {
        Thread t = new Thread(){
            @Override
            public void run() {
                System.out.println("hello thread");
            }
        };
        t.start();
    }
}

方法五: 使用了lambda表达式.

import java.util.*;
public class Demo5 {
    public static void main1(String[] args) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello thread");
            }
        });
        t.start();
    }

串行执行和并发执行

public class Demo7 {
    private static final long count = 10_0000_0000;

    public static  void serial(){
        //吉利程序执行时间
        long beg = System.currentTimeMillis();
        long a = 0;
        for (int i = 0; i < count; i++) {
            a++;
        }
        long b = 0;
        for (int i = 0; i < count; i++) {
            b++;
        }
        long end = System.currentTimeMillis();
        System.out.println("消耗时间: "+ (end - beg) + "ms");
    }
    public static void concurrency() throws InterruptedException {
        long beg = System.currentTimeMillis();
        Thread t1 = new Thread(()->{
            long a = 0;
            for (int i = 0; i < count; i++) {
                a++;
            }
        });
        t1.start();
        Thread t2 = new Thread(()->{
            long b = 0;
            for (int i = 0; i < count; i++) {
                b++;
            }
        });
        t2.start();
        //此处布恩那个直接记录结束时间,别忘了,现在这个时间戳的代码是在main 线程中
        //main t1 t2 是并发执行关系,此处t1 t2 还没执行完呢,这里就开始记录结束时间了,这显然是不准确的.
        //正确做法应该是让main线程等地啊t1 t2跑完了,在记录结束时间
        //join 效果就是等待线程结束,t1.join 就是让main 线程等待 t1 结束,t2.join让main 线程等待t2结束
        t1.join();
        t2.join();
        long end = System.currentTimeMillis();
        System.out.println("消耗时间: "+ (end - beg)+ "ms");
    }
    public static void main(String[] args)throws InterruptedException {
       // serial();
        concurrency();
    }
}

Thread中的一次额重要方法

1.start

决定了系统中是不是真的创建出线程,run单纯的是一个普通的方法,描述了任务的内容,start则是一个特殊的方法,内部会在系统中创建线程.

public class Demo9 {
    public static void main(String[] args) {
        Thread t = new Thread(()->{
            while (true) {
                System.out.println("hello thread1");
                try {
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
        t.start();
        //t.run();
        while (true) {
            System.out.println("hello main");
            try {
                Thread.sleep(1000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}

run方法只是一个普通的方法,在main线程里面调用run,其实并没有创建线程,这个循环仍是在main中执行的.

中断线程

中断线程:让一个线程停下来.

线程停下来的关键,是要让对应的run方法执行完.

(1).可以手动设置一个标志位,来控制线程是否要执行结束.

public class Demo10 {
    private  static boolean isQuit = false;
    public static void main(String[] args) {
        Thread t = new Thread(()->{
            while (!isQuit) {
                System.out.println("hello thread");
                try {
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
        t.start();
        //只要把这个isQuit 设为true ,此时这个循环就退出了,进一步run 就执行完了,再进一步就是线程结束了
        try{
            Thread.sleep(5000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        isQuit = true;
        System.out.println("终止t线程");
    }
}

(2).使用thread中内置的一个标志位来进行判定.

public class Demo11 {
    public static void main(String[] args) {
        Thread t = new Thread(()->{
            while(!Thread.currentThread().isInterrupted()){
                System.out.println("hello thread");
                try {
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                    //当触发异常之后,立即就退出循环
                    break;
                }
            }
        });
        t.start();
        try{
            Thread.sleep(5000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        //在线程中 调用interrupt 方法 来终端这个线程
        //t.interrupt 的意思是让t线程被中断!!
        t.interrupt();
    }
}

线程等待

多个线程之间,调度顺序是不确定的,线程之间的执行是按照调度器来安排的,这个过程可以视为无序或者随机的,有些时候,我们需要控制线程的顺序,线程等待就是其中一种手段,此处的线程等,主要控制线程结束的先后顺.

join: 调用join的时候,那个线程调用的join,那个线程就会阻塞等待,等到对应的线程执行完毕为止(对应线程的run执行完).

public class Demo12 {
    public static void main(String[] args) {
        Thread t = new Thread(()->{
            for (int i = 0; i < 5; i++) {
                System.out.println("hello thread");
                try{
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
        t.start();
        //在主线程中可以使用一个等待操作,来等待t线程执行结束
        try{
            t.join(10000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}

线程休眠(sleep)

如果线程调用了sleep方法,这个PCB就会进入到阻塞队列.

当睡眠时间到了,系统就会把这个PCB从阻塞队列挪回到就绪队列.

实例:

public class Demo14 {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(()->{
            while (true) {
                //z这里啥都不能有
                try{
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
        t.start();
        Thread.sleep(1000);
        System.out.println(t.getState());
    }
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们