第二十三章 多线程(一)

1. 多线程相关概念

1.1 并发(Concurrent)

        在操作系统中,是指一个时间段中有几个程序都处于已启动运行到运行完毕之间,且这几个程序都是在同一个处理机上运行;

        同一时刻只能有一条指令执行,但多个进程指令被快速的轮换执行,使得在宏观上具有多个进程同时执行的效果,但在微观上并不是同时执行的,只是把CPU时间分成若干段,使多个进程快速交替的执行。

1.2 并行(Parallel)

         当系统有一个以上CPU时,当一个CPU执行一个进程时,另一个CPU可以执行另一个进程,两个进程互不抢占CPU资源,可以同时进行,称之为并行;决定并行的因素是CPU核心数量,一个CPU多个核心也可以并行。

1.3 进程(Process)

        正在运行的程序实体,并且包括这个运行的程序中占据的所有系统资源(CPU(寄存器)、IO、内存、网络资源等);同一个程序,同一时刻被两次运行,那么他们就是两个独立的进程。

 1.4 线程(Thread)

        操作系统能够进行运算调度的最小单位;它被包含在进程中,是进程中的实际运作单位,一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。

1.5 多线程的优缺点

优点:

        ①可以让程序运行速度更快,用户在频繁切换运行进程的界面,界面下运行进程底层都有多个线程不断运行着,CPU一直处于运行状态;

        ②提高CPU利用率,大量线程同时处于运行状态,让CPU不间断运行;

缺点: 

        ①多线程情况,多个线程可能共享一个资源,如果资源数量有限,多线程竞争会产生等待问题;

        ②多线程,不断进行线程(上下文)切换,线程切换消耗资源;

        ③多线程,可能造成死锁。

2. 多线程实现方式

2.1 继承Thread类

public class MyThread extends Thread{
    private int ticket = 20;
    String name;

    public MyThread(String name) {
        this.name = name;
    }

    /**
     * 重写run方法,实现多线程执行业务的方法
     */
    @Override
    public void run() {
        while(ticket>0){
            System.out.println(Thread.currentThread().getName()+"  "+this.name+"卖出一张票,剩余:\t^"+(--ticket)+"^\t"+ LocalDateTime.now());
        }
    }
}

2.2 实现Runnable接口

Runnable接口可由任何类实现,其实例将由线程执行;必须定义无参方法run。

public class MyRunnable implements Runnable{
    private int ticket=20;
    @Override
    public void run() {
        while (ticket>0){
            System.out.println(Thread.currentThread().getName()+"卖出一张票,剩余:\t^"+(--ticket)+"^\t"+ LocalDateTime.now());
        }
    }
}

2.3 实现Callable接口

类似于Runnable接口,但Runnable不能返回结果,也不能抛出被检查的异常。

public class MyCallable implements Callable {
    /**
     * 线程的业务方法
     * @return
     * @throws Exception
     */
    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName()+"\t^"+i+"^\t"+ LocalDateTime.now());
            sum+=i;
        }
        return sum;
    }
}

 测试类:

public class MyTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyThread myThread = new MyThread("张三");
        myThread.start();

        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();

        MyCallable myCallable = new MyCallable();
        FutureTask ft = new FutureTask(myCallable);
        new Thread(ft).start();
        int res = (int)ft.get();
        System.out.println("++++++"+res+"+++++");
    }
}

2.4 线程池实现多线程

        Executors工厂和工具类Executor,ExecutorService,ScheduleExecutorService,ThreadFactory和Callable在此包中定义的类支持以下几种方法:

①创建并返回一个ExecutorService设置的常用的配置设置的方法;

②创建并返回一个ScheduledExecutorService的方法,其中设置了常用的配置设置;

③创建并返回"包装"ExecutorService的方法,通过使实现特定的方法无法访问来禁用重新配置;

④创建并返回将新创建的线程设置为已知状态的ThreadFactory的方法;

⑤创建并返回一个方法Callable出的其他闭包形式,这样就可以在需要的执行方法使用Callable。

public class MyTest2 {
    public static void main(String[] args) {
        MyThread myThread1 = new MyThread("张三");
        MyThread myThread2 = new MyThread("李四");
        MyThread myThread3 = new MyThread("王五");

        //启动多线程
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        executorService.execute(myThread1);
        executorService.execute(myThread2);
        executorService.execute(myThread3);

        //关闭线程池
        executorService.shutdown();
    }
}

2.5 实现runnable和继承thread的区别

        受Java单继承影响,继承thread无法实现成员变量(不使用特殊手段,加static),实现Runnable接口时,线程运行可以共享成员变量。

2.6 多线程常用方法

currentThread():返回对当前正在执行的线程对象的引用;

getName():返回此线程的名称;

run():当前启动的线程,执行业务的地方;

start():启动线程,让线程处于就绪状态;

setPriority():更改此线程的优先级,优先级是1~10之间的任意数字,默认值是5。

public class MyTest3 {
    public static void main(String[] args) {
        IA ia =new IA() {
            @Override
            public void test() {
                System.out.println("wan ^^");
            }
        };
        ia.test();

        Thread thread1 = new Thread("t1"){
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.println(Thread.currentThread().getName()+"对所有的烦恼说拜拜!"+"^"+i+"^");
                    if(i==5){
                        Thread.yield();
                    }
                }
            }
        };
        Thread thread2 = new Thread("t2"){
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.println(Thread.currentThread().getName()+"对所有的烦恼说拜拜!"+"^"+i+"^");
                    if(i%2==0){

                        Thread.yield();
                    }
                }
            }
        };
        Thread thread3 = new Thread("t3"){
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.println(Thread.currentThread().getName()+"对所有的烦恼说拜拜!"+"^"+i+"^");
                    if(i>0){
                        Thread.yield();
                    }
                }
            }
        };
        thread2.setPriority(Thread.MIN_PRIORITY);
        thread3.setPriority(Thread.MAX_PRIORITY);
        thread1.start();
        thread2.start();
        thread3.start();

    }
}

 2.7 多线程的状态

五种状态:

        新建(程序还没有开始运行线程中的代码)

        就绪(start方法返回之后就处于就绪状态,不一定直接运行run需要同其他线程竞争CPU时间)

        运行(线程获得CPU时间后,进入运行状态,执行run)

        阻塞(等待wait、带超时的等待sleep)

       终止(死亡,正常退出或者异常终止)

3. 综合练习

        使用Java程序,ping ip, 查看每个ip是否可以ping通;

package com.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.Buffer;

/**
 * @author :muxiaowen
 * @date : 2022/9/16 16:45
 */
public class PingUtil {
    public static long pingIp(String ip){
        long start = System.currentTimeMillis();
        System.out.println("------------");
        System.out.println(Thread.currentThread().getName());
        System.out.println("start:"+start);
        long end = 0;
        InputStream inputStream = null;
        BufferedReader br =null;
        try {
            //程序运行是的工具类
            Runtime runtime = Runtime.getRuntime();
            //执行cmd命令
            Process exec = runtime.exec("ping " + ip);
            //获取字节流
            inputStream = exec.getInputStream();
            //构建缓冲字符流
            br = new BufferedReader(new InputStreamReader(inputStream));
            String str= "";
            while ((str=br.readLine())!=null){
                System.out.println(str);
                if(str.contains("TTL")){
                    end = System.currentTimeMillis();
                    System.out.println(ip+"可以ping通");
                    System.out.println("end:"+end);
                    return end-start;
                }
                if(str.contains("Destination host unreachable")||str.contains("Request timed out")){
                    System.out.println(ip+"不可以ping通");
                    end = System.currentTimeMillis();
                    System.out.println("end:"+end);
                    return end-start;
                }
            }
            end = System.currentTimeMillis();
            System.out.println("end:"+end);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return end-start;
    }
}
public class MyPing implements Callable {
    private String ip;

    public MyPing(String ip) {
        this.ip = ip;
    }

    @Override
    public Object call() throws Exception {
        return PingUtil.pingIp(ip);
    }
}

测试类:

public class MyTest6 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long sum =  0;
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        for (int i = 0; i <= 120; i++) {
            MyPing myPing = new MyPing("192.168.0."+i);
            FutureTask ft = new FutureTask(myPing);
            executorService.execute(ft);
            sum += (long)ft.get();
        }
        System.out.println("+++++++++++++++++");
        System.out.println(sum);
        executorService.shutdown();
    }
}

不使用多线程速度会非常慢!

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值