栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【并发与多线程】Java多线程程序设计(三)锁案例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【并发与多线程】Java多线程程序设计(三)锁案例

目录
  • 背景知识
  • 锁实例
    • 卖票问题
      • 代码
    • 死锁
      • 代码
      • 结果演示
  • 综合案例:龟兔赛跑
      • 代码
      • 运行截图

背景知识

锁(LOCKING)是最常用的并发控制机构。是防止其他事务访问指定的资源控制、实现并发控制的一种主要手段。锁是事务对某个资源存取前,先向系统提出请求,封锁该资源,当操控的用户(或者说线程)获得锁后,即取得对数据的控制权,在系统释放它的锁之前,其他用户(或线程)不能更新此数据。当锁释放后,释放被锁定的资源。简单而言,当一个用户进程锁住某个对象时,其他用户进程就不能再访问和修改此对象。

锁实例 卖票问题

场景;6个人抢5张票

代码
public class Main {
    public static void main(String args[]) {
        MyThread mt = new MyThread() ; // 定义线程对象
        Thread t1 = new Thread(mt) ; // 定义 Thread 对象
        Thread t2 = new Thread(mt) ; // 定义 Thread 对象
        Thread t3 = new Thread(mt) ; // 定义 Thread 对象
        Thread t4 = new Thread(mt) ; // 定义 Thread 对象
        Thread t5 = new Thread(mt) ; // 定义 Thread 对象
        Thread t6 = new Thread(mt) ; // 定义 Thread 对象
        t1.start() ;
        t2.start() ;
        t3.start() ;
        t4.start() ;
        t5.start() ;
        t6.start() ;

    }
}
public class MyThread extends Thread{
    int ticket = 5 ; // 假设一共有 5 张票
    public void run(){
        for(int i=0;i<100;i++){
            synchronized(this) { //删掉本行的注释和下面括号的注释,再运行看看
                if (ticket > 0) { // 还有票
                    try {
                        Thread.sleep(300); // 这里模拟买票时的延迟,比如支付时间
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("卖票:ticket = " + ticket--);
                }
            }
        }
    }
}
死锁

拿筷子问题:每个人都等其他人放下筷子好让自己拿着,但是谁都不放,最终互相等待,陷入死循环。(双方都是一方解锁的条件依赖于另一方加锁的条件,双方相互制约)

代码
import java.util.concurrent.SynchronousQueue;

public class Main {
    public static void main(String args[]) {
        Runnable ming=new Runnable() {
            @Override
            public void run() {
                synchronized (Chop.chop1){
                    System.out.println("小明拿到了筷子1");
                    synchronized (Chop.chop2){
                        System.out.println("小明拿到了筷子2");
                    }
                }
            }
        };

        Runnable hong=new Runnable() {
            @Override
            public void run() {
                synchronized (Chop.chop2){
                    System.out.println("小红拿到了筷子1");
                    synchronized (Chop.chop1){
                        System.out.println("小红拿到了筷子2");
                    }
                }
            }
        };
        Thread thread1=new Thread(ming,"xiaoming");
        Thread thread2=new Thread(hong,"xiaohong");
        thread1.start();
        thread2.start();
    }
}

public class Chop {
        static String chop1="这是筷子1";
        static String chop2="这是筷子2";
}
结果演示

综合案例:龟兔赛跑 代码
public class Race {
    public static String winner;
    public static int maxStep = 100;
    public static void main(String[] args) {
        Animal animal = new Animal();
        Thread tortoise = new Thread(animal, "乌龟");
        Thread rabbit = new Thread(animal, "兔子");
        tortoise.start();
        rabbit.start();
    }
}

class Animal implements Runnable{
    private static String winner;
    private static int maxStep=100;
    @Override
    public void run() {
        for (int i = 0; i <=maxStep; i++) {
            if(!Thread.currentThread().isInterrupted()){
                if(Thread.currentThread().getName().equals("兔子")){
                    try{
                        Thread.sleep(100);
                        if(i==maxStep/2){
                            System.out.println("兔子跑了一半路程,要开始睡大觉了!");
                            Thread.sleep(12000);
                            System.out.println("兔子睡醒了,要开始继续赶路了!");
                        }
                    }catch(InterruptedException e){
                        e.getStackTrace();
                    }
                }else{
                    try{
                        Thread.sleep(400);
                    }catch(InterruptedException e){
                        e.getStackTrace();
                    }
                }
                if(winner!=null){
                    Thread.currentThread().interrupt();
                    return ;
                }
                System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
                if(isWinner(i)){
                    System.out.println(winner+"赢得了比赛");
                    Thread.currentThread().interrupt();
                }
            }
        }
    }

    private boolean isWinner(int step){
        if(step>=maxStep) {
            winner=Thread.currentThread().getName();
            return true;
        }
        return false;
    }
}

运行截图

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/985487.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号