Java 多线程
一、实现多线程
1.1 进程
进程:是正在运行的程序
- 是系统进行资源分配和调用的独立单位
- 每一个进程都有它自己的内存空间和系统资源
1.2 线程
线程:是进程中的单个顺序控制流,是一条执行路径
- 单线程:一个进程如果只有一条执行路径,则称为单线程程序
- 多线程:一个进程如果有多条执行路径,则称为多线程程序
1.3 多线程的实现方式
多线程的实现方案有两种:
- 继承Thread类
- 实现Runnable接口
方式1:继承Thread类
- 定义一个MyThread类继承Thread类
- 在MyThread类中重写run()方法
- 创建MyThread类的对象
- 启动线程
为什么要重写run()方法呢?
- 因为run()是用来封装被线程执行的代码
run()和start()方法的区别?
- run():封装线程执行的代码,直接调用,相当于普通方法的调用
- start():启动线程;然后由JVM调用此线程run()方法
public class MyThread extends Thread{
@Override
public void run(){
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
}
}
public class ThreadDemo1 {
public static void main(String[] args) {
MyThread myThread1 = new MyThread();
MyThread myThread2 = new MyThread();
myThread1.start();
myThread2.start();
}
}
方式2:实现Runnable接口
- 定义一个MyRunnable实现Runnable接口
- 在MyRunnable类中重写run()方法
- 创建MyRunable类的对象
- 创建Thread类的对象,把MyRunnable对象作为构造方法的参数
- 启动线程
public class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
public class MyRunnableDemo {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
// Thread thread1 =new Thread(myRunnable);
// Thread thread2 =new Thread(myRunnable);
//Thread (Runable target,String name)
Thread thread1 =new Thread(myRunnable,"a");
Thread thread2 =new Thread(myRunnable,"b");
thread1.start();
thread2.start();
}
}
相比继承Thread类,实现Runnable接口的好处
- 避免了Java单继承的局限性
- 适合多个相同程序的代码去处理同一个资源的情况,把线程和程序的代码、数据有效分离,较好的体现了面向对象的设计思想
1.4 设置和获取线程名称
Thread类中设置和获取线程名称的方法
- void setName(String name):将此线程的名称更改为等于参数name
- String getName():返回此线程的名称
- 通过构造方法也可以设置线程名称
如何获取main()方法所在的线程名称?
- public static Thread currentThread():返回对当前正在执行的线程对象的引用
System.out.println(Thread.currentThread().getName());
public class MyThread extends Thread {
MyThread(){
}
MyThread(String name){
super(name);
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(getName() + ":" + i);
}
}
}
public class ThreadDemo2 {
public static void main(String[] args) {
MyThread myThread1 = new MyThread("线程1");
MyThread myThread2 = new MyThread("线程2");
// myThread1.setName("线程1");
// myThread2.setName("线程2");
myThread1.start();
myThread2.start();
System.out.println(Thread.currentThread().getName());
}
}
1.5 线程调度
线程有两种调度模型
- 分时调度模型:所有线程轮流使用CPU的使用权,平均分配每个线程占用CPU的时间片
- 抢占式调度模型:优先让优先级高的线程使用CPU,如果线程的优先级相同,那么会随机选择一个,优先级高的线程获取的CPU时间片相对多一些
java使用的是抢占式调度模型
加入计算机只有一个CPU,那么CPU在某一个时刻只能执行一条指令,线程只有得到CPU时间片,也就是使用权,才可以执行指令。所以说多线程程序执行是有随机性,因为谁抢到CPU的使用权是不一定的。
Thread类中设置和获取线程优先级的方法:
- public final int getPriority():返回此线程的优先级
- public final void setPriority(int newPriority):更改此线程的优先级
- 线程默认优先级是5;线程优先级的范围是:1-10
- 线程优先级高仅仅是表示线程获取的CPU时间片的几率高,但是要在次数比较多,或者多次运行的时候才能看到你想要的效果
public class ThreadPriorityDemo {
public static void main(String[] args) {
ThreadPriority threadPriority1 = new ThreadPriority();
ThreadPriority threadPriority2 = new ThreadPriority();
ThreadPriority threadPriority3 = new ThreadPriority();
threadPriority1.setName("线程1");
threadPriority2.setName("线程2");
threadPriority3.setName("线程3");
System.out.println(threadPriority1.getPriority()); //默认5
System.out.println(threadPriority2.getPriority());
System.out.println(threadPriority3.getPriority());
System.out.println(Thread.MIN_PRIORITY); //1
System.out.println(Thread.NORM_PRIORITY); //5
System.out.println(Thread.MAX_PRIORITY); //10
threadPriority1.setPriority(5);
threadPriority2.setPriority(10);
threadPriority3.setPriority(1);
threadPriority1.start();
threadPriority2.start();
threadPriority3.start();
}
}
1.6 线程控制
方法名 | 说明 |
---|---|
static void sleep(long millis) | 使当前正在执行的线程停留(暂停执行)指定的毫秒数 |
void join() | 等待这个线程死亡 |
void setDaemon(boolean on) | 将此线程标记为守护线程,当运行的线程都是守护线程时,Java虚拟机将退出 |
- static void sleep(long millis)
public class ThreadSleep extends Thread{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(getName() + ":" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadSleepDemo {
public static void main(String[] args) {
ThreadSleep threadSleep1 = new ThreadSleep();
ThreadSleep threadSleep2 = new ThreadSleep();
ThreadSleep threadSleep3 = new ThreadSleep();
threadSleep1.setName("a");
threadSleep2.setName("b");
threadSleep3.setName("c");
threadSleep1.start();
threadSleep2.start();
threadSleep3.start();
}
}
- void join()
public class ThreadJoinDemo {
public static void main(String[] args) throws InterruptedException {
ThreadJoin threadJoin1 = new ThreadJoin();
ThreadJoin threadJoin2 = new ThreadJoin();
ThreadJoin threadJoin3 = new ThreadJoin();
threadJoin1.setName("a");
threadJoin2.setName("b");
threadJoin3.setName("c");
threadJoin1.start();
threadJoin1.join();
threadJoin2.start();
threadJoin3.start();
}
}
- void setDaemon(boolean on)
public class ThreadDaemonDemo {
public static void main(String[] args) {
ThreadDaemon threadDaemon1 = new ThreadDaemon();
ThreadDaemon threadDaemon2 = new ThreadDaemon();
threadDaemon1.setName("张飞");
threadDaemon2.setName("关羽");
threadDaemon1.setDaemon(true);
threadDaemon2.setDaemon(true);
threadDaemon1.start();
threadDaemon2.start();
Thread.currentThread().setName("刘备");
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
1.7 线程生命周期
- 新建(创建线程对象)
- start()
- 就绪(有执行资格没有执行权)
- 抢到CPU执行权
- 运行(有执行资格,执行权)
- run()结束/stop()
- 死亡(线程死亡变成垃圾)
二、线程同步
2.1 卖票案例
案例卖票:
需求:某电影院目前正在上映国产大片,共有100张票,而它有3个窗口卖票,设计一个程序模拟该电影院卖票
public class SellTicket implements Runnable {
private int tickets = 100;
@Override
public void run() {
while (true) {
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
tickets--;
}
}
}
}
public class SellTicketDemo {
public static void main(String[] args) {
SellTicket sellTicket = new SellTicket();
Thread thread1 = new Thread(sellTicket,"窗口1");
Thread thread2 = new Thread(sellTicket,"窗口2");
Thread thread3 = new Thread(sellTicket,"窗口3");
thread1.start();
thread2.start();
thread3.start();
}
}
出现的问题:
- 相同的票出现了多次
- 出现了负数的票
原因:
- 线程执行的随机性导致的
2.2 卖票案例数据安全问题的解决
判断多线程程序是否会有数据安全问题的标准
- 是否是多线程环境
- 是否有数据共享
- 是否有多条语句操作共享数据
如何解决多线程安全问题?
- 让程序没有安全问题的环境
如何实现?
- 把多条语句操作共享数据的代码锁起来,让任意时刻只能有一个线程执行即可
2.3 同步代码块
锁多条语句操作共享数据,可以使用同步代码实现
- 格式:
synchronized(任意对象){
多条语句操作共享数据的代码
}
- synchronized(任意对象):就相当于给代码加锁了,任意对象久就可以看成是一把锁
同步的好处和弊端:
- 好处:解决了多线程的数据安全问题
- 弊端:当线程很多时,因为每个线程都会去判断同步上的锁,这是很耗费资源的,无形中会降低程序的
运行效率
public class SellTicket implements Runnable {
private int tickets = 100; //共享数据
private Object lock = new Object();
@Override
public void run() {
while (true) {
synchronized (lock) {
if (tickets > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
tickets--;
}
}
}
}
}
public class SellTicketDemo {
public static void main(String[] args) {
SellTicket sellTicket = new SellTicket();
Thread thread1 = new Thread(sellTicket,"窗口1");
Thread thread2 = new Thread(sellTicket,"窗口2");
Thread thread3 = new Thread(sellTicket,"窗口3");
thread1.start();
thread2.start();
thread3.start();
}
}
2.4 同步方法
同步方法:就是把synchronized关键字加到方法上
修饰符 synchronized 返回值类型 方法名(方法参数){}
同步方法的的锁对象是什么呢?
- this
同步静态方法:就是把synchronized关键字加到静态方法上
修饰符 static synchronized 返回值类型 方法名(方法参数){}
同步静态方法的的锁对象是什么呢?
- 类名.class
public class SellTicket implements Runnable {
private int tickets = 100;
private Object lock = new Object();
private int x = 0;
@Override
public void run() {
while (true) {
if (x % 2 == 0) {
synchronized (this) {
if (tickets > 0) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
tickets--;
}
}
} else {
sellTicket();
}
x++;
}
}
private synchronized void sellTicket() {
if (tickets > 0) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
tickets--;
}
}
}
public class SellTicketDemo {
public static void main(String[] args) {
SellTicket sellTicket = new SellTicket();
Thread thread1 = new Thread(sellTicket,"窗口1");
Thread thread2 = new Thread(sellTicket,"窗口2");
Thread thread3 = new Thread(sellTicket,"窗口3");
thread1.start();
thread2.start();
thread3.start();
}
}
2.5 线程安全的类
StringBuffer
- 线程安全,可变的字符序列。
- 从版本JDK5开始,这个类别已经被一个等级类补充了,这个类被设计为使用一个线程StringBuilder 。StringBuilder应该使用StringBuilder类,因为它支持所有相同的操作,但它更快,因为它不执行同步。
Vector
- 从Java 2平台v1.2,这个类被改造为实现List接口,使其成为成员Java Collections Framework 。与新集合实现不同,Vector是同步的。如果不需要线程安全的实现,建议使用ArrayList代替Vector 。
Hashtable
- 该类实现了一个哈希表,它将键映射到值。 任何非null对象都可以用作键值或值。
- 从Java 2平台v1.2,这个类被改造为实现Map接口,使其成为成员Java Collections Framework 。与新的集合实现不同, Hashtable是同步的。 如果不需要线程安全的实现,建议使用HashMap代替Hashtable 。 如果需要线程安全的并发实现,那么建议使用ConcurrentHashMap代替Hashtable 。
2.6 Lock锁
虽然我们可以理解同步代码和同步方法的锁对象问题,但是我们并没有直接看到在哪里加上了锁,在哪里释放了锁,为了更清晰的表达如何加锁和释放锁,JDK5以后提供了一个新的锁对象Lock
Lock实现提供比使用synchronized方法和语句可以获得更广泛的锁定操作
Lock中提供了获得锁和释放锁的方法
- void lock():获得锁
- void unloc:释放锁
Lock是接口不能直接实例化,这里采用它的实现类ReentrantLock来实例化
ReentrantLock的构造方法
- ReentrantLock():创建一个ReentrantLock的实例
public class SellTicket implements Runnable {
private int tickets = 100;
private Lock lock = new ReentrantLock();
@Override
public void run() {
lock.lock();
try {
while (true) {
if (tickets > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
tickets--;
}
}
} finally {
lock.unlock();
}
}
}
public class SellTicketDemo {
public static void main(String[] args) {
SellTicket sellTicket = new SellTicket();
Thread thread1 = new Thread(sellTicket,"窗口1");
Thread thread2 = new Thread(sellTicket,"窗口2");
Thread thread3 = new Thread(sellTicket,"窗口3");
thread1.start();
thread2.start();
thread3.start();
}
}
三、生产者和消费者
3.1 生产者消费者模式概述
生产者消费者模式是一个十分经典的多线程协作的模式,弄懂生产消费者问题能够让我们对多线程编程的理解更加深刻,所谓生产者消费者问题,实际上主要包含了两类线程:
- 一类是生产者线程用于生产数据
- 一类是消费者线程用于消费数据
为了解耦生产者和消费者的关系,通常会采用共享的数据区域,就像是一个仓库
- 生产者生产数据之后直接放置在共享数据区中,并不需要关系消费者的行为
- 消费者只需要从共享数据区中去获取数据,并不关心生产者的行为
为了体现生产者和消费者过程中的等待和唤醒,Java就提供了几个方法供我们使用,这几个方法在Object类中Object类的等待和唤醒方法:
方法名 | 说明 |
---|---|
void wait() | 导致当前线程等待,直到另一个线程调用该对象的notify()方法或notifyAll()方法 |
void notify() | 唤醒正在等待对象监视器的单个线程 |
void notifyAll() | 唤醒正在等待对象监视器的所有线程 |
3.2 生产者消费者案例
public class Box {
private int milk;
private boolean state = false;
public synchronized void put(int milk) {
if (state) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.milk = milk;
System.out.println("送奶工将第" + this.milk + "瓶奶放入奶箱");
state = true;
notifyAll();
}
public synchronized void get() {
if (!state) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("用户拿到第" + this.milk + "瓶奶");
state = false;
notifyAll();
}
}
public class Producer implements Runnable{
private Box box;
public Producer(Box box) {
this.box = box;
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
box.put(i);
}
}
}
public class Customer implements Runnable{
private Box box;
public Customer(Box box) {
this.box = box;
}
@Override
public void run() {
while (true){
box.get();
}
}
}
public class BoxDemo {
public static void main(String[] args) {
Box box = new Box();
Producer producer = new Producer(box);
Customer customer = new Customer(box);
Thread thread1 =new Thread(producer);
Thread thread2 =new Thread(customer);
thread1.start();
thread2.start();
}
}
运行结果:
送奶工将第1瓶奶放入奶箱
用户拿到第1瓶奶
送奶工将第2瓶奶放入奶箱
用户拿到第2瓶奶
送奶工将第3瓶奶放入奶箱
用户拿到第3瓶奶
送奶工将第4瓶奶放入奶箱
用户拿到第4瓶奶
送奶工将第5瓶奶放入奶箱
用户拿到第5瓶奶
每个人的人生都有两条路,一条用心走,叫做梦想;一条用脚走,叫做现实。如果心走得太慢,现实就会苍白;而如果脚走得太慢,梦想就不会高飞。人生的精彩,莫过于心走得很美,且与脚步合一。不忘初心,脚踏实地,你就可以创造独有的精彩。