Java多线程的学习

63 阅读1分钟

什么是多线程

进程:计算机正在运行的一个应用程序,动态的概念

线程:线程是组成进程的基本单位 进程的每一个任务都用一个线程来表示

Java中如何使用线程

Thread 类来表示线程,每一个Thread 对象就是一个线程

Runnable 接口表示任务

线程一定和任务绑定

一个线程对应一个任务,没有任务的线程是没有意义的,任务也不能脱离线程独立存在

自定义类 继承 Thread类

Thread 类是父类 由开发者自主进行扩展

自定义类 并且继承

对修改关闭(JDK 源码) 对扩展(自定义类)开放

线程本质上就是争夺 CPU 资源 执行对应的任务

线程执行一定调用 start方法 而不能调用 run 方法

run 正序执行

start 是交错执行 并行执行

public class MyThread2 extends Thread{    @Override    public void run() {        for (int i = 0; i < 100; i++) {            System.out.println("嘻嘻嘻嘻2222");        }    }}

public class MyThread extends Thread{​    @Override    public void run() {        for (int i = 0; i < 100; i++) {            System.out.println("嘻嘻嘻1111");        }    }}// 按两次 Shift 打开“随处搜索”对话框并输入 `show whitespaces`,// 然后按 Enter 键。现在,您可以在代码中看到空格字符。public class Main {    public static void main(String[] args) {             MyThread myThread = new MyThread();             myThread.start();​             MyThread2 MY = new MyThread2();             MY.start();        }    }​

上述方法存在弊端 线程和任务耦合度过高 不利于程序的扩展

高内聚 低耦合

如何解决

实现Runnable 接口

将线程和任务分开 单独创建任务 然后将任务交给线程

public class MyRunnable2 implements Runnable {​    @Override    public void run() {        System.out.println("hello Runnable");    }}

//将多线程的任务抽离出来MyRunnable myRunnable = new MyRunnable();MyRunnable2 myRunnable2 = new MyRunnable2();Thread thread = new Thread(myRunnable2);thread.start();