多线程基础

多线程基础

1.线程的相关概念

1.1 进程

进程就是正在执行的程序.是程序的一次执行过程,有他自身的创建,存在和消亡的过程.

1.2线程

线程是由进程创建的,属于进程,是进程的一个实体,一个进程可以有多个线程.

1.3单线程和多线程

单线程就是一个线程同一个时刻只允许执行一个线程.

多线程就是一个进程同一个时刻可以执行多个线程.比如一个百度网盘可以同时下载多个文件.

1.4并发

同一个时刻,多个任务交替执行,造成一种"好像同时"的错觉.

单个CPU实现的多任务就是并发

1.5并行

同一个时刻,多个任务一起执行.

多核CPU可以实现并行

2.线程的创建

在Java中,创建Java有三种方式,分别是继承Tread类,实现Runnable接口,实现Callable接口

2.1 继承Thread类

通过继承Tread类创建线程的步骤为

  1. 创建一个类去继承Tread类
  2. 重写Tread类的run()方法,写入我们的业务代码
  3. 创建该类对象,调用start()方法启动线程
public class MyThread extends Thread{
    @Override
    public void run() {
        System.out.println("十七张牌你能秒我?");
    }
}
public class Test {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}

同样,我们也可以使用匿名内部类的方式去创建对象来调用start()方法

public class Test {
    public static void main(String[] args) {
        Thread thread = new Thread(){
            @Override
            public void run() {
                System.out.println("我是学习时长两年半的Java实习生");
            }
        };
        thread.start();
    }
}
2.2 实现Runnable接口

通过实现Runnable接口创建线程的步骤为

  1. 创建一个类去实现Runnable接口
  2. 重写Runnable类的run()方法,写入我们的业务代码
  3. 创建该类对象
  4. 创建Thread对象,将该类对象传入Tread的构造方法
  5. 调用Thread对象的start()方法启动线程
public class MyRunnable implements Runnable{
    @Override
    public void run() {
        System.out.println("Java学的好,头发没得早");
    }
}
public class Test {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
}

同样也可以使用匿名内部类的方法

public class Test {
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("学什么Java,肝游戏去了");
            }
        });
        thread.start();
    }
}
2.3 实现Callable接口

通过实现Callable接口创建线程的方式如下

  1. 创建一个类去实现Runnable接口
  2. 重写Runnable类的run()方法,写入我们的业务代码
  3. 创建该类对象,将该对象用FutureTask类进行包装
  4. 创建Thread对象,将包装后的对象传入Tread的构造方法

5.调用Thread对象的start()方法启动线程

public class MyCallable implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        System.out.println("你是");
        return 250;
    }
}
public class Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyCallable myCallable = new MyCallable();
        FutureTask<Integer> ft = new FutureTask<Integer>(myCallable);
        Thread thread = new Thread(ft);
        thread.start();
        System.out.println(ft.get());
    }
}

二者的区别就是Callable接口的call()方法是有返回值的

3. run()和start()的区别

run()方法其实就是一个普通的方法,并不会真正启动一个线程,真正启动一个线程是start()方法

public class ThreadDemo extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println(i + "-线程名:"+Thread.currentThread().getName());
            //Thread.currentThread().getName()获取当前线程的线程名
        }
    }
}
public class Test {
    public static void main(String[] args) {
        ThreadDemo thread = new ThreadDemo();
        thread.run();
        for (char i = 'a'; i < 'g'; i++) {
            System.out.println(i + "-线程名:" + Thread.currentThread().getName());
        }
    }
}

image

可以发现,run()方法就是一个普通的方法,在只调用run()方法时是和主线程为同一个线程,只会顺序执行

public class Test {
    public static void main(String[] args) {
        ThreadDemo thread = new ThreadDemo();
        thread.start();
        for (char i = 'a'; i < 'g'; i++) {
            System.out.println(i + "-线程名:" + Thread.currentThread().getName());
        }
    }
}

image

当我们去调用start()方法时,才是真正去创建启动一个线程,去调用run()方法,可以看到默认线程名是Thread-0,与主线程main交替执行.

多线程案例:

4.线程的常用方法

4.1 static native Thread currentThread()

返回当前的线程对象

4.2 String getName()

获取当前线程名

Thread thread = new Thread(() -> {
    System.out.println("给阿姨倒一杯卡布奇诺");
});
String name = thread.getName();
System.out.println("当前线程名是:" + name);
4.3 void setName(String name)

设置当前线程名

thread.setName("土块");
System.out.println("更改后的线程名是:" + thread.getName());
4.4 int getPriority()

获取线程优先级.线程的优先级是int类型的,范围从1-10,数字越大优先级越高

int priority = thread.getPriority();
System.out.println(priority);
4.5 void setPriority(String name)

设置线程优先级

thread.setPriority(10);
System.out.println(thread.getPriority());
4.6 static native void sleep(long millis)

线程休眠,让线程休眠一段时间,单位是毫秒

long startTime = System.currentTimeMillis();
try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    throw new RuntimeException(e);
}
long endTime = System.currentTimeMillis();
long time = endTime - startTime;
System.out.println("经过了" + time + "毫秒");
4.7 void interrupt()

中断线程,但是并不会真正结束线程.通常用于干扰正在睡眠的线程,线程睡眠被强行唤醒会抛出一个异常

public class ThreadDemo {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(1000 * 60 * 60 * 60);//睡眠1小时
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("小黑子食不食油饼");
        });
        thread.start();
        try {
            Thread.sleep(1000);//让主线程休眠1秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.interrupt();//强行唤醒睡眠的线程
    }
}

image

4.8 void join()

线程插队.

线程抢占到CPU执行权后优先执行完该线程的所有操作

public class ThreadDemo08 {
    public static void main(String[] args) throws InterruptedException {
        //创建一个线程打印字母
        Thread thread = new Thread(() -> {
            for (char c = 'a'; c <= 'z'; c++) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.print(c);
            }
        });
        thread.start();
        for (int i = 0; i < 10; i++) {
            Thread.sleep(100);
            System.out.print(i);
            if (i == 5) {//当i=5时,让thread线程插队
                thread.join();
            }
        }
    }
}
4.9 static native void yield()

线程的礼让.

此方法会让出已经抢占到的CPU执行权,但是礼让的时间不确定,礼让后还会和其他线程抢夺CPU执行权,所以不一定礼让成功

5.用户线程和守护线程

5.1用户线程

用户线程也叫工作线程,当线程的任务执行完或通知方式结束

5.2守护线程

守护线程一般是为工作线程而服务的,当所有的用户线程结束,守护线程自动结束

线程默认是用户线程,通过setDaemon(true)可以将一个线程设置为守护线程.

public static void main(String[] args) {
    Thread thread = new Thread(() -> {
        for (int i = 1; i < 100; i++) {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("第" + i + "个小黑子");
        }
    });
    thread.setDaemon(true);//将线程设置为守护线程
    thread.start();
    for (int i = 1; i < 5; i++) {
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("第" + i + "个小黑子食不食油饼");
    }
}
image

可以发现,当主线程结束后,守护线程也会结束

6.线程的生命周期

6.1线程的生命周期

线程的生命周期就是指线程从创建到销毁的过程.线程的生命周期可以分为以下五种:

New(新建),Runnable(可运行),Blocking(阻塞),Waiting(无限期等待),Time Waiting(有限期等待),Terminated(死亡)

线程的状态转换如图所示:

image

6.1.1. New(新建)

New状态就是新建了一个线程但并未调用start()启动线程

6.2.2. Runnable(可运行)

调用start()方法后线程进入Runnable状态,操作系统把此状态分为Runnable(可运行)和Ready(就绪状态)

此时线程可能正在运行,也有可能未抢占到CPU资源处于Ready等待执行

6.2.3. Blocking(阻塞)

线程进入锁之后就会处于Blocking状态,等待线程释放锁解除此状态

6.2.4. Waiting(无限期等待)

调用Object的wait()方法或通过其他方式进入Waiting状态,等待其他线程将其显式将其唤醒,否则不会继续执行

进入方法退出方法
没有设置Timeout 参数Object.wait()方法Object.notify() / Object.notifyAll()
没有设置 Timeout 参数Thread.join() 方法被调用的线程执行完毕
LockSupport.park() 方法
6.2.5. Time Waiting(限期等待)
进入方法退出方法
Thread.sleep() 方法时间结束
设置了 Timeout 参数的 Object.wait() 方法时间结束 / Object.notify() / Object.notifyAll()
设置了 Timeout 参数的 Thread.join() 方法时间结束 / 被调用的线程执行完毕
LockSupport.parkNanos() 方法-
LockSupport.parkUntil() 方法-
6.2.6. Terminated(死亡)

线程结束任务后正常结束或产生异常而结束

6.2 模拟线程的各种状态
public class ThreadDemo03 {
    public static void main(String[] args) throws InterruptedException {
        //创建四个线程
        Thread thread1 = new Thread(() -> {
            try {
                Thread.sleep(100);//确保thread1后进入同步代码块,便于观察到BLOCKED状态
                synchronized (LockInterface.LOCK) {
                    Thread.sleep(500);//用于观察线程的TIMED_WAITING状态
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        Thread thread2 = new Thread(() -> {
            try {
                Thread.sleep(50);//确保先于thread1进入同步代码块
                synchronized (LockInterface.LOCK) {
                    Thread.sleep(300);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        });
        Thread thread3 = new Thread(() -> {
            synchronized (LockInterface.LOCK) {
                try {
                    LockInterface.LOCK.wait();//调用wait()方法,用来观察线程的Waiting状态
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread thread4 = new Thread(() -> {
            try {
                Thread.sleep(100);//确保thread3先进入同步代码块
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            synchronized (LockInterface.LOCK) {
                LockInterface.LOCK.notify();//用来唤醒thread3
            }
        });
        thread1.setName("thread1");
        thread3.setName("thread3");
        System.out.println(thread1.getName() + "状态是: " + thread1.getState());//获取线程状态
        thread1.start();
        thread2.start();
        System.out.println(thread1.getName() + "状态是: " + thread1.getState());
        Thread.sleep(100);
        while (Thread.State.TERMINATED != thread1.getState()) {
            System.out.println(thread1.getName() + "状态是: " + thread1.getState());
            Thread.sleep(400);//限制打印次数
        }
        thread3.start();
        thread4.start();
        while (Thread.State.TERMINATED != thread3.getState()) {
            Thread.sleep(50);//限制打印次数
            System.out.println(thread3.getName() + "状态是: " + thread3.getState());

        }
    }
}

7.线程的同步

以食油饼为例,共有10张油饼,创建2个线程去食油饼

public class OilCake implements Runnable {
    private static int num = 10;

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if (num == 0) {
                return;
            }
            num--;
            System.out.println(Thread.currentThread().getName() + "食了一张油饼," + "还剩" + num + "张油饼");
        }
    }
}
public class Test {
    public static void main(String[] args) {
        OilCake oilCake = new OilCake();
        Thread thread1 = new Thread(oilCake);
        Thread thread2 = new Thread(oilCake);
        thread1.setName("大司马");
        thread2.setName("卢姥爷");
        thread1.start();
        thread2.start();
    }
}

image

我们发现,数据产生了错乱,出现了线程安全问题,造成此种问题的原因是,两个线程可能同时操作数据

,为了处理这种问题,我们就需要用到线程同步机制

7.1 线程同步机制
7.1.1 同步代码块

在使用多线程编程时,有时候我们不希望一些敏感数据被多个线程同时访问,此时就需要使用到线程同步机制,保证在同一时刻只能有一个线程去访问这个数据,来保证数据的完整性,这时就可以使用同步代码块.

同步代码块的语法如下,把需要同步的代码用同步代码块进行包裹,同步代码块的关键字是synchronized

synchronized(锁对象){
    //需要进行同步的代码
}

用同步代码块来改写食油饼案例

public class OilCake implements Runnable {
    private static int num = 10;

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if (num == 0) {
                return;
            }
           synchronized (this){
               num--;
               System.out.println(Thread.currentThread().getName() + "食了一张油饼," + "还剩" + num + "张油饼");
           }
        }
    }
}
public class Test {
    public static void main(String[] args) {
        OilCake oilCake = new OilCake();
        Thread thread1 = new Thread(oilCake);
        Thread thread2 = new Thread(oilCake);
        thread1.setName("大司马");
        thread2.setName("卢姥爷");
        thread1.start();
        thread2.start();
    }
}

image

7.1.2 同步方法

synchronized还可以用来修饰方法,被修饰的非静态方法就是同步方法

public synchronized void method(String param){
    //需要进行同步的代码
}
7.1.3 静态同步方法

用synchronized修饰的静态方法就是同步静态方法

public synchronized static void method(xxx.class){
            //需要进行同步的代码
}

线程同步通俗的讲就相当于两个人一起上厕所蹲坑,一个占到坑位后关上门(上锁),上完厕所后打开门(释放锁),此时另一个人才能接着上

7.2互斥锁

Java中引入了对象互斥锁的概念,以用来保证数据的完整性,每个对象都有一个对应可称为"互斥锁"的标记,以使在任一时刻只能有一个线程访问该对象

关键字synchronized用来与对象的互斥锁进行关联.

同步方法的锁可以是this,也可以是其他对象,静态同步方法的锁是当前类本身对象

7.3 线程的死锁

多个线程都占用了对方的锁但资源不肯想让,就会导致死锁

用个简单的例子来讲就是:

家长:你先写完作业,再去玩游戏

孩子:我先玩完游戏,再去写作业

两个人都不肯相让,导致了死锁

public class ThreadLock implements Runnable{
    private static final Object o1 = new Object();//创建一个静态常量用来上锁
    private static final Object o2 = new Object();//创建一个静态常量用来上锁
    private boolean loop = true;

    public ThreadLock(boolean loop) {
        this.loop = loop;
    }

    @Override
    public void run() {
        if (loop) {//如果loop为true,则进入o1锁
            synchronized (o1){
                System.out.println(Thread.currentThread().getName()+"进入了o1锁");
                synchronized (o2){
                    System.out.println(Thread.currentThread().getName()+"进入了o2锁");
                }
            }
        }else {//如果loop为false,则进入o2锁
            synchronized (o2){
                System.out.println(Thread.currentThread().getName()+"进入了o2锁");
                synchronized (o1){
                    System.out.println(Thread.currentThread().getName()+"进入了o1锁");
                }
            }
        }
    }
}
public class ThreadDemo {
    public static void main(String[] args) {
        ThreadLock lock1 = new ThreadLock(true);//给loop
        ThreadLock lock2 = new ThreadLock(false);
        Thread thread1 = new Thread(lock1);//让线程1先进入o1锁
        Thread thread2 = new Thread(lock2);//让线程2先进入o2锁
        thread1.setName("线程1");
        thread2.setName("线程2");
        thread1.start();
        thread2.start();
    }
}
7.5 Object中和线程有关的方法
7.5.1 void wait()

让线程进入无限期休眠

7.5.2 void wait(long timeout)

让线程进入有限期休眠,单位是毫秒

7.5.3 void wait(long timeout, int nanos)

让线程进入有限期休眠,单位是毫秒+纳秒

7.5.4 void notify()

随机唤醒一个正在休眠的线程

7.5.5 void notifyAll()

唤醒所有休眠的线程

//用两个线程分别打印数字1~26和字母a~z,要求格式是1a2b...25y26z
public class ThreadDemo04 {
    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            synchronized (LockInterface.LOCK) {
                for (int i = 1; i < 27; i++) {
                        System.out.println(i);
                        try {
                            LockInterface.LOCK.notify();
                            if (i != 26) {
                                LockInterface.LOCK.wait();
                            }
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
        });
        Thread thread2 = new Thread(() -> {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            synchronized (LockInterface.LOCK) {
                for (char i = 'a'; i <= 'z'; i++) {
                    System.out.println(i);
                    try {
                        LockInterface.LOCK.notify();
                        if (i != 'z') {
                            LockInterface.LOCK.wait();
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });
        thread1.start();
        thread2.start();
    }
}

7.6 锁的释放

在同一时刻,只有一个线程可以访问同步代码块,直到锁被释放

以下的操作会释放锁:

  1. 当前线程的同步方法或同步代码块执行结束

    例:正常上厕所,上完出来

  2. 当前线程的同步方法或同步代码遇到break,return跳出

    例:上厕所上到一半,被女生喊出来帮忙改代码

  3. 当前的同步方法或同步代码块遇到了未处理的异常

    例:上厕所上到一半发现忘带纸了,不得已出来

  4. 当前线程在同步代码块或同步代码块执行了wait()方法

    例:上厕所蹲了半天发现没有屎意,所以出去等有屎意再去上

以下的操作不会释放锁:

  1. 线程执行同步方法或同步代码块时,遇到Thread.sleep()方法

    例:上厕所上到一半太困了睡着了

  2. 线程执行同步代码块时,其他线程调用了该线程的suspend()方法将线程挂起

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值