多线程基础
第一章 线程简介
程序.进程.线程
-
Java 给多线程编程提供了内置的支持。 一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。
-
多线程是多任务的一种特别的形式,但多线程使用了更小的资源开销。
-
这里定义和线程相关的另一个术语 - 进程:一个进程包括由操作系统分配的内存空间,包含一个或多个线程。一个线程不能独立的存在,它必须是进程的一部分。一个进程一直运行,直到所有的非守护线程都结束运行后才能结束。
-
多线程能满足程序员编写高效率的程序来达到充分利用 CPU 的目的。
线程的生命周期
新建状态
使用 new 关键字和 Thread 类或其子类建立一个线程对象后,该线程对象就处于新建状态。它保持这个状态直到程序 start() 这个线程。
就绪状态
当线程对象调用了start()方法之后,该线程就进入就绪状态。就绪状态的线程处于就绪队列中,要等待JVM里线程调度器的调度
运行状态
如果就绪状态的线程获取 CPU 资源,就可以执行 run(),此时线程便处于运行状态。处于运行状态的线程最为复杂,它可以变为阻塞状态、就绪状态和死亡状态。
阻塞状态
如果一个线程执行了sleep(睡眠)、suspend(挂起)等方法,失去所占用资源之后,该线程就从运行状态进入阻塞状态。在睡眠时间已到或获得设备资源后可以重新进入就绪状态。可以分为三种:
- 等待阻塞:运行状态中的线程执行 wait() 方法,使线程进入到等待阻塞状态。
- 同步阻塞:线程在获取 synchronized 同步锁失败(因为同步锁被其他线程占用)。
- 其他阻塞:通过调用线程的 sleep() 或 join() 发出了 I/O 请求时,线程就会进入到阻塞状态。当sleep() 状态超时,join() 等待线程终止或超时,或者 I/O 处理完毕,线程重新转入就绪状态。
死亡状态
一个运行状态的线程完成任务或者其他终止条件发生时,该线程就切换到终止状态。
线程的优先级
-
每一个 Java 线程都有一个优先级,这样有助于操作系统确定线程的调度顺序。
-
Java 线程的优先级是一个整数,其取值范围是 1 (Thread.MIN_PRIORITY ) - 10 (Thread.MAX_PRIORITY )。
-
默认情况下,每一个线程都会分配一个优先级 NORM_PRIORITY(5)。
-
具有较高优先级的线程对程序更重要,并且应该在低优先级的线程之前分配处理器资源。但是,线程优先级不能保证线程执行的顺序,而且非常依赖于平台。
核心概念
- 线程就是独立的执行路径
- 在程序运行时,即使没有自己创建线程,后台也会有多个线程,比如主线程,GC线程
- main()称之为主线程,为系统的入口,用于执行整个程序
- 在一个进程中,如果开辟了多个线程,线程的运行是由调度器(cpu)安排调度的,调度器是与操作系统紧密相关的,先后顺序是不能人为干预的
- 对同一份资源操作时mm会存在资源抢夺的问题,需要加入并发控制
- 线程会带来额外的开销,如CPU调度时间,并发控制开销
- 每个线程在自己的工作内存交互,内存控制不当会造成数据不一致
第二章 线程实现
Java 提供了三种创建线程的方法:
- 通过实现 Runnable 接口;
- 通过继承 Thread 类本身;
- 通过 Callable 和 Future 创建线程。
线程创建(三种方法)
实现Runnable接口
- 创建一个线程,最简单的方法是创建一个实现 Runnable 接口的类。
- 为了实现 Runnable,一个类只需要执行一个方法调用 run(),声明如下:
public void run()
- 你可以重写该方法,重要的是理解的 run() 可以调用其他方法,使用其他类,并声明变量,就像主线程一样。
- 在创建一个实现 Runnable 接口的类之后,你可以在类中实例化一个线程对象。
- Thread 定义了几个构造方法,下面的这个是我们经常使用的:
Thread(Runnable threadOb,String threadName);
- 这里,threadOb 是一个实现 Runnable 接口的类的实例,并且 threadName 指定新线程的名字。
- 新线程创建之后,你调用它的 start() 方法它才会运行。
void start();
下面是一个创建线程并开始让它执行的实例:
public class TestThread {
public static void main(String args[]) {
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
}
}
class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo( String name) {
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// 让线程睡眠一会
Thread.sleep(10);
}
}catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
继承Thread类(重要)
- 创建一个线程的第二种方法是创建一个新的类,该类继承 Thread 类,然后创建一个该类的实例。
- 继承类必须重写 run() 方法,该方法是新线程的入口点。它也必须调用 start() 方法才能执行。
- 该方法尽管被列为一种多线程实现方式,但是本质上也是实现了 Runnable 接口的一个实例
public class TestThread {
public static void main(String args[]) {
ThreadDemo T1 = new ThreadDemo( "Thread-1");
T1.start();
ThreadDemo T2 = new ThreadDemo( "Thread-2");
T2.start();
}
}
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
ThreadDemo( String name) {
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// 让线程睡眠一会
Thread.sleep(50);
}
}catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
实现Callable接口(了解)
-
创建 Callable 接口的实现类,并实现 call() 方法,该 call() 方法将作为线程执行体,并且有返回值。
-
创建 Callable 实现类的实例,使用 FutureTask 类来包装 Callable 对象,该 FutureTask 对象封装了该 Callable 对象的 call() 方法的返回值。
-
使用 FutureTask 对象作为 Thread 对象的 target 创建并启动新线程。
-
调用 FutureTask 对象的 get() 方法来获得子线程执行结束后的返回值。
public class CallableThreadTest implements Callable<Integer> {
public static void main(String[] args)
{
CallableThreadTest ctt = new CallableThreadTest();
FutureTask<Integer> ft = new FutureTask<>(ctt);
for(int i = 0;i < 100;i++)
{
System.out.println(Thread.currentThread().getName()+" 的循环变量i的值"+i);
if(i==20)
{
new Thread(ft,"有返回值的线程").start();
}
}
try
{
System.out.println("子线程的返回值:"+ft.get());
} catch (InterruptedException e)
{
e.printStackTrace();
} catch (ExecutionException e)
{
e.printStackTrace();
}
}
@Override
public Integer call() throws Exception
{
int i = 0;
for(;i<100;i++)
{
System.out.println(Thread.currentThread().getName()+" "+i);
}
return i;
}
}
三种方法的对比
-
采用实现 Runnable、Callable 接口的方式创建多线程时,线程类只是实现了 Runnable 接口或 Callable 接口,还可以继承其他类。
-
使用继承 Thread 类的方式创建多线程时,编写简单,如果需要访问当前线程,则无需使用 Thread.currentThread() 方法,直接使用 this 即可获得当前线程。
注意
在多线程编程时,你需要了解以下几个概念:
- 线程同步
- 线程间通信
- 线程死锁
- 线程控制:挂起、停止和恢复
静态代理
实例
/**
* 静态代理:结婚案例
*/
public class Demo7_StaticProxy {
public static void main(String[] args) {
WeddingCompany weddingCompany = new WeddingCompany(new You());
weddingCompany.happyMarry();
}
}
//结婚
interface Marry {
void happyMarry();
}
//真实角色:你去结婚
class You implements Marry {
@Override
public void happyMarry() {
System.out.println("doris要结婚了,超开心");
}
}
//代理角色:帮助你结婚
class WeddingCompany implements Marry {
private Marry target;//代理-->真实目标角色角色,帮谁结婚
public WeddingCompany(Marry target) {
this.target = target;
}
@Override
public void happyMarry() {
after();
this.target.happyMarry();
before();
}
private void after() {
System.out.println("结婚之前,布置现场");
}
private void before() {
System.out.println("结婚之后,收尾款");
}
}
总结
- 真实对象和代理对象都要实现一个接口
- 代理对象要代理真实角色
好处
- 代理对象可以做很多真实对象做不了的事情
- 真实对象专注做自己的事
Lamda表达式
- Lambda 表达式,也可称为闭包,它是推动 Java 8 发布的最重要新特性。
- Lambda 允许把函数作为一个方法的参数(函数作为参数传递进方法中)。
Face -> 函数式接口:对于任何接口,如果只包含一个抽象方法; - 使用 Lambda 表达式可以使代码变的更加简洁紧凑。
(parameters) -> expression
或
(parameters) ->{ statements; }
- Lambda 表达式实例
public class Java8Tester {
public static void main(String args[]){
Java8Tester tester = new Java8Tester();
// 类型声明
MathOperation addition = (int a, int b) -> a + b;
// 不用类型声明
MathOperation subtraction = (a, b) -> a - b;
// 大括号中的返回语句
MathOperation multiplication = (int a, int b) -> { return a * b; };
// 没有大括号及返回语句
MathOperation division = (int a, int b) -> a / b;
System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
System.out.println("10 / 5 = " + tester.operate(10, 5, division));
// 不用括号
GreetingService greetService1 = message ->
System.out.println("Hello " + message);
// 用括号
GreetingService greetService2 = (message) ->
System.out.println("Hello " + message);
greetService1.sayMessage("Runoob");
greetService2.sayMessage("Google");
}
interface MathOperation {
int operation(int a, int b);
}
interface GreetingService {
void sayMessage(String message);
}
private int operate(int a, int b, MathOperation mathOperation){
return mathOperation.operation(a, b);
}
}
使用 Lambda 表达式需要注意以下两点:
- Lambda 表达式主要用来定义行内执行的方法类型接口,例如,一个简单方法接口。在上面例子中,我们使用各种类型的Lambda表达式来定义MathOperation接口的方法。然后我们定义了sayMessage的执行。
- Lambda 表达式免去了使用匿名方法的麻烦,并且给予Java简单但是强大的函数化的编程能力。
第三章 线程方法
停止线程
建议使用标志位让线程停止
/**
* 测试stop
* 1.建议线程正常停止-->利用次数,不建议死循环
* 2.建议使用标志位-->设置一个标志位
* 3.不要使用stop或者destroy等过时或者JDK不建议使用的方法
*/
public class Demo15_StopThread implements Runnable {
// 1. 设置一个标志位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag) {
System.out.println("run...Thread" + i++);
}
}
// 2. 设置一个公开的方法停止线程,转换标志位
public void stop() {
this.flag = false;
}
public static void main(String[] args) {
Demo15_StopThread stop = new Demo15_StopThread();
new Thread(stop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main..." + i);
if (i == 900) {
//调用stop()切换标志位,让线程终止
stop.stop();
System.out.println("该线程停止了");
}
}
}
}
线程休眠
sleep制定了当前阻塞的毫秒数;
sleep可以模拟网络延时,倒计时等等;
每个线程都有一个锁,sleep不会释放锁;
public class Thread1 implements Runnable {
//票数
private int ticketNums = 10;
public static void main(String[] args) {
Thread1 ticket = new Thread1();
new Thread(ticket, "小红").start();
new Thread(ticket, "老师").start();
new Thread(ticket, "黄牛1").start();
}
@Override
public void run() {
while (true) {
if (ticketNums <= 0) {
break;
}
//捕获异常
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "--->拿到了第" + ticketNums-- + "张票");
}
}
}
- 获取每一刻的时间
public class Thread1 implements Runnable {
public static void main(String[] args) {
Date startT = new Date(System.currentTimeMillis());
while(true){
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startT));
startT = new Date(System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
}
}
线程礼让
- yield()
- 让当前正在执行的线程暂停,但不阻塞;
- 将线程从运行状态转为就绪状态;
- 让cpu重新调度,礼让不一定成功;
public class ThreadYield {
public static void main(String[] args) {
yield yield = new yield();
new Thread(yield,"a").start();
new Thread(yield,"b").start();
}
}
class yield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" = start");
Thread.yield();
System.out.println(Thread.currentThread().getName() + " = end");
}
}
线程插队
- join()
- 当前线程挂起,先执行插入的线程;
public class ThreadYield implements Runnable {
@Override
public void run() {
for (int i = 0; i < 500; i++) {
System.out.println("线程vip" + i);
}
}
public static void main(String[] args) throws InterruptedException {
//启动我们的线程
ThreadYield joinThread = new ThreadYield();
Thread thread = new Thread(joinThread);
thread.start();
//主线程
for (int i = 0; i < 500; i++) {
if (i == 200) {
thread.join();//插队
}
System.out.println("main" + i);
}
}
}
线程状态观测
Thread.State
/**
* 观察测试线程状态
*/
public class Demo21_ThreadState {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("//");
});
//观察状态
Thread.State state = thread.getState();
System.out.println(state);
//观察启动后
thread.start();
state = thread.getState();
System.out.println(state);//Run
while (state != Thread.State.TERMINATED) {//只要现成不终止,就一直输出状态
Thread.sleep(100);
state = thread.getState();//更新线程状态
System.out.println(state);
}
//死亡后的线程不能再启动了,启动会报异常
//thread.start();
}
}
线程优先级
-
每一个 Java 线程都有一个优先级,这样有助于操作系统确定线程的调度顺序。
-
Java 线程的优先级是一个整数,其取值范围是 1 (Thread.MIN_PRIORITY ) - 10 (Thread.MAX_PRIORITY )。
-
默认情况下,每一个线程都会分配一个优先级 NORM_PRIORITY(5)。
-
具有较高优先级的线程对程序更重要,并且应该在低优先级的线程之前分配处理器资源。但是,线程优先级不能保证线程执行的顺序,而且非常依赖于平台
/**
* 线程优先级
*/
public class Demo22_ThreadPriority{
public static void main(String[] args) {
//主线程默认优先级
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread thread1 = new Thread(myPriority);
Thread thread2 = new Thread(myPriority);
Thread thread3 = new Thread(myPriority);
Thread thread4 = new Thread(myPriority);
Thread thread5 = new Thread(myPriority);
//先设置优先级,再启动
thread1.start();
thread2.setPriority(1);
thread2.start();
thread3.setPriority(4);
thread3.start();
thread4.setPriority(Thread.MAX_PRIORITY);//MAX_PRIORITY=10
thread4.start();
thread5.setPriority(8);
thread5.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}
守护线程
- 线程分为:用户线程和守护线程;
- jvm必须要保证用户线程执行完毕;
- jvm不需要确保守护线程执行完毕;
/**
* 测试守护线程
* 上帝守护你
*/
public class Demo23_DaemonThread {
public static void main(String[] args) {
God god = new God();
You you = new You();
Thread thread = new Thread(god);
//默认false表示是用户线程,正常的线程都是用户线程...
thread.setDaemon(true);
//上帝守护线程启动
thread.start();
//你 用户线程启动
new Thread(you).start();
}
}
//上帝
class God implements Runnable{
@Override
public void run() {
while (true){
System.out.println("上帝保佑着你");
}
}
}
//你
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("你一生都开心的活着");
}
System.out.println("====goodbye!world====");
}
}
第四章 线程同步
- 并发:同一个对象被多个线程同时操作
- 队列和锁:由于同一及进程的多个线程共享同一块存储空间,为了保证数据在方法中被访问的正确性,在访问时加入了锁机制synchronized,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可;
三大不安全的线程案例
模拟购票app
public class ThreadYield {
public static void main(String[] args) {
Ticketer ticketer = new Ticketer();
new Thread(ticketer, "小明").start();
new Thread(ticketer, "小红").start();
new Thread(ticketer, "小李").start();
new Thread(ticketer, "小宋").start();
new Thread(ticketer, "大黄").start();
}
}
//售票大厅
class Ticketer implements Runnable{
private int num = 10;
boolean flag = true;
@Override
public void run() {
while(flag){
try {
buy();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void buy() {
if(num<=0){
flag = false;
return;
}
//模拟延迟
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " get " + num-- );
}
}
线程不安全,出现了负数;
/**
* 不安全的取钱
*/
public class Demo25_UnsafeBank {
public static void main(String[] args) {
Account account = new Account(100, "结婚基金");
Drawing you = new Drawing(account, 50, "展堂");
Drawing girlfriend = new Drawing(account, 100, "sad");
you.start();
girlfriend.start();
}
}
//账户
class Account {
int money;//余额
String cardName;//卡名
public Account(int money, String cardName) {
this.money = money;
this.cardName = cardName;
}
}
//银行:模拟取款
class Drawing extends Thread {
Account account;//账户
int drawingMoney;//取金额
int nowMoney;//你手里的钱
public Drawing(Account account, int drawingMoney, String name) {
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
//取钱
@Override
public void run() {
//判断是否有钱
if (account.money - drawingMoney < 0) {
System.out.println(Thread.currentThread().getName() + "余额不足,不能进行取钱");
return;
}
try {
Thread.sleep(1000);//放大问题的发生性
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内金额 = 余额-你的钱
account.money = account.money - drawingMoney;
//你手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(account.cardName + "余额为:" + account.money);
//this.getName()==Thread.currentThread().getName()
System.out.println(this.getName() + "手里的钱:" + nowMoney);
}
}
public class ThreadYield {
//线程不安全的集合
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
System.out.println(list.size());
}
}
同步方法和同步块
//安全买票
public class Demo24_UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket ticketer = new BuyTicket();
new Thread(ticketer, "小明").start();
new Thread(ticketer, "小红").start();
new Thread(ticketer, "小李").start();
new Thread(ticketer, "小宋").start();
new Thread(ticketer, "大黄").start();
}
}
class BuyTicket implements Runnable {
//票
private int ticketNums = 10;
boolean flag = true;
@Override
public void run() {
//买票
while (flag) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
buy();
}
}
//买票
private synchronized void buy() {
//判断是否有票
if (ticketNums <= 0) {
flag = false;
return;
}
//买票
System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
}
}
/**
* 安全的取钱 同步块
*/
public class Demo25_UnsafeBank {
public static void main(String[] args) {
Account1 account = new Account1(100, "结婚基金");
Drawing1 you = new Drawing1(account, 50, "展堂");
Drawing1 girlfriend = new Drawing1(account, 100, "sad");
you.start();
girlfriend.start();
}
}
//账户
class Account1 {
int money;//余额
String cardName;//卡名
public Account1(int money, String cardName) {
this.money = money;
this.cardName = cardName;
}
}
//银行:模拟取款
class Drawing1 extends Thread {
Account1 account;//账户
int drawingMoney;//取金额
int nowMoney;//你手里的钱
public Drawing1(Account1 account, int drawingMoney, String name) {
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
//取钱
@Override
public void run() {
//锁的对象就是变量的量,需要增删改查的对象
synchronized (account) {
//判断是否有钱
if (account.money - drawingMoney < 0) {
System.out.println(Thread.currentThread().getName() + "余额不足,不能进行取钱");
return;
}
try {
Thread.sleep(1000);//放大问题的发生性
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内金额 = 余额-你的钱
account.money = account.money - drawingMoney;
//你手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(account.cardName + "余额为:" + account.money);
//this.getName()==Thread.currentThread().getName()
System.out.println(this.getName() + "手里的钱:" + nowMoney);
}
}
}
public class ThreadYield {
//线程不安全的集合
public static synchronized void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
死锁
/**
* 死锁:多个线程互相抱着对方需要的资源,然后形成僵持
* 解决:一个锁只锁一个对象
*/
class Demo31_DeadLock {
public static void main(String[] args) {
Makeup makeup = new Makeup(0, "灰姑娘");
Makeup makeup1 = new Makeup(1, "白雪公主");
makeup.start();
makeup1.start();
}
}
//口红
class Lipstick { }
//镜子
class Mirror { }
class Makeup extends Thread {
//需要的资源只有一份,用static保证只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice;//选择
String girlName;//使用化妆品的人
public Makeup(int choice, String girlName) {
this.choice = choice;
this.girlName = girlName;
}
@Override
public void run() {
//化妆
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void makeup() throws InterruptedException {
if (choice == 0) {
synchronized (lipstick) {//获得口红的锁
System.out.println(this.girlName + "获得口红的锁");
Thread.sleep(1000);
synchronized (mirror) {//一秒钟后想获得镜子
System.out.println(this.girlName + "获得镜子的锁");
}
}
} else {
synchronized (mirror) {//获得口红镜子
System.out.println(this.girlName + "获得镜子的锁");
Thread.sleep(2000);
synchronized (lipstick) {//二秒钟后想获得的锁
System.out.println(this.girlName + "获得口红的锁");
}
}
}
}
}
避免死锁
- 防止互相抱锁
private void makeup() throws InterruptedException {
if (choice == 0) {
synchronized (lipstick) {//获得口红的锁
System.out.println(this.girlName + "获得口红的锁");
Thread.sleep(1000);
}
synchronized (mirror) {//一秒钟后想获得镜子
System.out.println(this.girlName + "获得镜子的锁");
}
} else {
synchronized (mirror) {//获得口红镜子
System.out.println(this.girlName + "获得镜子的锁");
Thread.sleep(800);
}
synchronized (lipstick) {//二秒钟后想获得的锁
System.out.println(this.girlName + "获得口红的锁");
}
}
}
Lock(锁)
//测试Lock锁
public class Demo32_ThreadLock {
public static void main(String[] args) {
TestLock testLock = new TestLock();
new Thread(testLock).start();
new Thread(testLock).start();
new Thread(testLock).start();
}
}
class TestLock implements Runnable {
int tickerNums = 10;
//定义Lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
//加锁
try {
lock.lock();
if (tickerNums <= 0) {
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(tickerNums--);
} catch (Exception e) {
e.printStackTrace();
} finally {
//解锁
lock.unlock();
}
}
}
}
synchroized与Lock对比
第五章 线程通信问题
生产者消费者模式
生产者消费者模式
管程法
/**
* 测试:生产者消费者模型-->利用缓冲区解决:管程法
*/
public class Demo33_ThreadPC {
public static void main(String[] args) {
SynContainer synContainer = new SynContainer();
new Producer(synContainer).start();
new Consumer(synContainer).start();
}
}
//生产者
class Producer extends Thread {
//容缓冲区
SynContainer container;
public Producer(SynContainer container) {
this.container = container;
}
//生产
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.push(new Product(i));
System.out.println("生产了" + i + "件产品");
}
}
}
//消费者
class Consumer extends Thread {
//容缓冲区
SynContainer container;
public Consumer(SynContainer container) {
this.container = container;
}
//消费
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了-->" + container.pop().id + "件产品");
}
}
}
//产品
class Product {
int id;//产品编号
public Product(int id) {
this.id = id;
}
}
//缓冲区
class SynContainer {
//需要一个容器大小
Product[] products = new Product[10];
//容器计数器
int count = 0;
//生产者放入产品
public synchronized void push(Product product) {
//如果容器满了,需要等待消费者消费
/*如果是if的话,假如消费者1消费了最后一个,这是index变成0此时释放锁被消费者2拿到而不是生产者拿到,这时消费者的wait是在if里所以它就直接去消费index-1下标越界,如果是while就会再去判断一下index得值是不是变成0了*/
while (count == products.length) {
//通知消费者消费,等待生产
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没有满,需要丢入产品
products[count] = product;
count++;
//通知消费者消费
this.notifyAll();
}
//消费者消费产品
public synchronized Product pop() {
//判断是否能消费
while (count <= 0) {
//等待生产者生产
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果可以消费
count--;
Product product = products[count];
//吃完了 通知生产者生产
this.notifyAll();
return product;
}
}
信号灯法
- 设定标志位flag()和唤醒线程notify()
/**
* 测试:生产者消费者模型-->利用缓冲区解决:管程法
*/
public class Demo33_ThreadPC {
public static void main(String[] args) {
SynContainer synContainer = new SynContainer();
new Producer(synContainer).start();
new Consumer(synContainer).start();
}
}
//生产者
class Producer extends Thread {
//容缓冲区
SynContainer container;
public Producer(SynContainer container) {
this.container = container;
}
//生产
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.push(new Product(i));
System.out.println("生产了" + i + "件产品");
}
}
}
//消费者
class Consumer extends Thread {
//容缓冲区
SynContainer container;
public Consumer(SynContainer container) {
this.container = container;
}
//消费
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了-->" + container.pop().id + "件产品");
}
}
}
//产品
class Product {
int id;//产品编号
public Product(int id) {
this.id = id;
}
}
//缓冲区
class SynContainer {
//需要一个容器大小
Product[] products = new Product[10];
//容器计数器
int count = 0;
//生产者放入产品
public synchronized void push(Product product) {
//如果容器满了,需要等待消费者消费
/*如果是if的话,假如消费者1消费了最后一个,这是index变成0此时释放锁被消费者2拿到而不是生产者拿到,这时消费者的wait是在if里所以它就直接去消费index-1下标越界,如果是while就会再去判断一下index得值是不是变成0了*/
while (count == products.length) {
//通知消费者消费,等待生产
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没有满,需要丢入产品
products[count] = product;
count++;
//通知消费者消费
this.notifyAll();
}
//消费者消费产品
public synchronized Product pop() {
//判断是否能消费
while (count <= 0) {
//等待生产者生产
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果可以消费
count--;
Product product = products[count];
//吃完了 通知生产者生产
this.notifyAll();
return product;
}
}
第六章 线程池
//测试线程池
public class Demo35_ThreadPool {
public static void main(String[] args) {
// 1. 创建服务,擦行间线程池
// newFixedThreadPool(线程池大小)
ExecutorService service = Executors.newFixedThreadPool(10);
//执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//关闭连接
service.shutdown();
}
}
class MyThread implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}