线程的基本使用

1. 线程概念

  • 程序:是为完成特定任务,用某种语言编写的一组指令的集合。简单理解就是我们写的代码。
  • 进程:运行中的程序,比如我们使用QQ,就启动 一个进程,操作系统会为该进程分配内存空间;当我们使用微信,就又启动 一个进程,操作系统会为该进程分配新的内存空间;
    进程是程序的一次执行过程,或者是正在运行的程序,是动态的过程,有它自身的产生,存在和消亡的过程。
  • 线程:线程由进程创建,是进程的一个实体,一个进程可以拥有多个线程
    单线程:同一时刻,只允许执行一个线程
    多线程:同一时刻,可以执行多个线程
  • 并发:同一时刻,多个任务交替执行,造成“貌似同时”的错觉,单核cpu实现的多任务就是并发
  • 并行:同一时刻,多个任务同时执行。

2. 线程的基本使用

创建线程的两种方式

2.1 继承Thread类,重写run方法

start方法会调用start0(),该线程不一定会立马执行,只是将该线程置为可执行状态,由CPU进行调度。
start0()是本地方法,是JVM调用,底层是c/c++实现
真正实现多线程的是start0(),而不是run

public class Thread01 {
    public static void main(String[] args) throws InterruptedException{
        Cat cat = new Cat();
        cat.start(); //启动线程->最终会执行cat的run方法
        System.out.println("主线程名:" + Thread.currentThread().getName());
        // 说明:当main线程启动一个子线程Thread-0,主线程不会阻塞,会继续执行
        // 这时主线程和子线程是交替执行..
        for (int i = 0; i < 5; i++) {
            System.out.println("主方法" + i + " 线程名:" + Thread.currentThread().getName());
            Thread.sleep(1000);
        }
    }
}

class Cat extends Thread {
    @Override
    public void run() {
        int times = 0;
        while (true) {
            System.out.println("小猫咪" + times++ + " 线程名:" + Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (times > 8) {
                break;
            }
        }
    }
}

2.2 实现Runnable接口

Java是单继承的,如果一个类A已经继承了类B,这是就无法让类A再去继承THread了,所以还有方法2----实现Runnable接口,底层使用了代理模式

public class Thread02 {
    public static void main(String[] args)
    {
        Dog dog = new Dog();
        //dog.start(); 这里不能调用 start
        //创建了 Thread 对象,把 dog 对象(实现 Runnable),放入 Thread
        Thread thread = new Thread(dog);
        thread.start();
        // Tiger tiger = new Tiger();//实现了 Runnable
        // ThreadProxy threadProxy = new ThreadProxy(tiger);
        // threadProxy.start();
    }
}

class Dog implements Runnable { //通过实现 Runnable 接口,开发线程
    int count = 0;
    @Override
    public void run() { //普通方法
        while (true) {
            System.out.println("小狗汪汪叫..hi" + (++count) + Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (count == 10) {
                break;
            }
        }
    }
}

3. 多线程的基本使用

public class Thread03 {
    public static void main(String[] args) {
        T1 t1 = new T1();
        T2 t2 = new T2();
        Thread thread1 = new Thread(t1);
        Thread thread2 = new Thread(t2);
        thread1.start();//启动第 1 个线程
        thread2.start();//启动第 2 个线程
        //... 
    }
}
class T1 implements Runnable {
    int count = 0;
    @Override
    public void run() {
        while (true) {
            //每隔 1 秒输出 “hello,world”,输出 10 次
            System.out.println("hello,world " + (++count));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(count == 60) {
                break;
            }
        }
    }
}
class T2 implements Runnable {
    int count = 0;
    @Override
    public void run() {
    //每隔 1 秒输出 “hi”,输出 5 次
        while (true) {
            System.out.println("hi " + (++count));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(count == 50) {
                break;
            }
        }
    }
}

3. 线程终止

当线程完成任务后,会自动退出
还可以通过使用变量来控制run方法退出的方式停止线程,即通知方式

4. 线程常用方法

setName // 设置线程名称
getName
start
run
setPriority // 更改优先级
getPriority
sleep
interrupt // 中断线程
yield // 礼让,但是礼让的时间不确定,也不一定礼让成功
join // 线程插队,一旦插队成功,则执行完插入线程的所有任务

5. 守护线程

用户线程:也叫工作线程,当线程的任务执行完成或通知方式结束
守护线程:一般是为工作线程服务的,当所有的用户线程结束,守护线程自动结束,垃圾回收机制就是各典型的守护线程

public class DaemonThreadTest {
    public static void main(String[] args) {
        MyDaemonThread daemonThread = new MyDaemonThread();
        daemonThread.setDaemon(true);
        daemonThread.start();
        for (int i = 0 ; i < 10; i++) {
            System.out.println("妈妈下班了");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class MyDaemonThread extends Thread {
    @Override
    public void run() {
        while(true) {
            System.out.println("小朋友在家看电视");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

6. 线程的生命周期

6.1 JDK中用Thread.State枚举表示了线程的几种状态

在这里插入图片描述

6.2 线程状态转换图

在这里插入图片描述
写程序查看线程状态

public class ThreadState_ {
	public static void main(String[] args) throws InterruptedException {
		T t = new T();
		System.out.println(t.getName() + " 状态 " + t.getState());
		t.start();
		while (Thread.State.TERMINATED != t.getState()) {
			System.out.println(t.getName() + " 状态 " + t.getState());
			Thread.sleep(500);
		}
		System.out.println(t.getName() + " 状态 " + t.getState());
	}
}
class T extends Thread {
	@Override
	public void run() {
		while (true) {
			for (int i = 0; i < 10; i++) {
				System.out.println("hi " + i);
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			break;
		}
	}
}

7. 线程的同步

当一个线程在对某些数据进行操作时,其他线程都不可以对这些数据进行操作,直到该线程完成操作,其他线程才能对这些数据进行操作

7.1 同步具体方法-Synchronized
  1. 同步代码块
synchronized (对象) { // 得到对象的锁,才能操作同步代码
	// 需要同步的代码
}
  1. 同步方法
public synchronized void m() {
	// 需要同步的代码
}
7.2 互斥锁

1、Java语言中,引入了对象互斥锁的概念,来保证共享数据操作的完整性。
2、每个对象都对应一个可称为“互斥锁”的标记,这个标记用来保证在任一时刻,只能有一个线程访问该对象。
3、关键字syncchronized来与对象的互斥锁联系。当某个对象用syncchronized修饰时,表明该对象在任一时刻只能由一个线程访问。
4、同步的局限性:导致程序的执行效率要降低。
5、同步方法(非静态的)的锁可以是this,也可以是其他对象(要求是同一个对象)
6、同步方法(静态的)的锁为当前类本身。

同步方法(静态的)的锁为当前类本身

/**
 * Created by hq on 2024/11/4.
 */
public class Ticket {
    public static void main(String[] args) {
        Ticket01 t1 = new Ticket01();
        Thread thread1 = new Thread(t1);
        Thread thread2 = new Thread(t1);
        Thread thread3 = new Thread(t1);
        thread1.start();
        thread2.start();
        thread3.start();

//        Ticket02 t1 = new Ticket02();
//        Ticket02 t2 = new Ticket02();
//        Ticket02 t3 = new Ticket02();
//        t1.start();
//        t2.start();
//        t3.start();

    }
}

class Ticket01 implements Runnable {
    private int ticketNum = 100;
    Object object = new Object();
    //1. public synchronized void sellTicket() {} 就是一个同步方法
    //2. 这时锁在 this 对象
    //3. 也可以在代码块上写 synchronize ,同步代码块, 互斥锁还是在 this 对象

    public synchronized int sellTicket() {
//        synchronized (/*this*/ object) {
//
//        }
        if (ticketNum <= 0) {
            System.out.println("已售罄!");
            return -1;
        }
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("窗口" + Thread.currentThread().getName() + "售出1张票,剩余票数:" + --ticketNum);
        return 0;
    }
    @Override
    public void run() {
        while (true) {
            if (sellTicket() < 0) {
                break;
            }
        }
    }

    //同步方法(静态的)的锁为当前类本身
    //1. public synchronized static void m1() {} 锁是加在 SellTicket03.class
    //2. 如果在静态方法中,实现一个同步代码块.
    public synchronized static void m1() {
    }
    public static void m2() {
        synchronized (Ticket01.class) {
            System.out.println("m2");
        }
    }
}

class Ticket02 extends Thread{
    private static int ticketNum = 100;

    public int sellTicket() {
        if (ticketNum <= 0) {
            System.out.println("已售罄!");
            return -1;
        }
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("窗口" + Thread.currentThread().getName() + "售出1张票,剩余票数:" + --ticketNum);
        return 0;
    }
    @Override
    public void run() {
        while (true) {
            if (sellTicket() < 0) {
                break;
            }
        }
    }
}

8. 线程死锁

多个线程占用了对方的锁资源,但不肯相让,导致了死锁。
类似于:

妈妈:你写完作业才可以玩手机
小明:我先玩手机才能写作业

模拟死锁代码

/**
 * Created by hq on 2024/11/5.
 */
public class DeadLock {
    public static void main(String[] args) {
        DeadLock01 deadLock01 = new DeadLock01(true);
        DeadLock01 deadLock02 = new DeadLock01(false);
        deadLock01.start();
        deadLock02.start();
    }
}

class DeadLock01 extends Thread{
    static Object o1 = new Object();
    static Object o2 = new Object();
    private boolean flag;

    public DeadLock01(boolean flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        if (flag) {
            synchronized (o1) {
                System.out.println("o1进入");
                synchronized (o2) {
                    System.out.println("o2进入");
                }
            }
        } else {
            synchronized (o2) {
                System.out.println("o2进入...");
                synchronized (o1) {
                    System.out.println("o1进入...");
                }
            }
        }
    }
}

8.1 释放锁
  1. 同步方法或同步代码块结束
  2. 同步方法或同步代码块中遇到break、return
  3. 当前线程在同步方法或同步代码块中出现了未处理的Error或异Exception,导致异常结束
  4. 当前线程在同步方法或同步代码块中执行了线程对象的wait方法,当前线程暂停,并释放锁

下面的操作不会释放锁:

  1. 线程执行同步方法或同步代码块时,程序调用Thread.sleep、Thread.yield方法暂停当前线程,不会释放锁
  2. 挂起方法也不会
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值