JAVA题目笔记(二十四)多线程 (run方法原理)

news/2024/12/16 5:48:34/

一、卖电影票


public class Main {public static void main(String[] args)  {//创建线程对象 Ticket t1=new Ticket("电影院一:");Ticket t2=new Ticket("电影院二:");t1.start();t2.start();}
}import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class Ticket extends Thread{//1000张电影票private static int count=100;public Ticket(){}public Ticket(String name){super(name);}//创建一个锁private static Lock lock=new ReentrantLock();@Overridepublic void run() {while(true){//上锁lock.lock();try {if(count==0){System.out.println("电影票卖完了");break;}else {Thread.sleep(30);count--;System.out.println(this.getName()+"卖了一张票,还剩下"+count+"张票");}} catch (InterruptedException e) {throw new RuntimeException(e);} finally {//解锁lock.unlock();}}}
}

二、送礼物


public class Main {public static void main(String[] args)  {//创建线程对象Ticket t1=new Ticket("小明");Ticket t2=new Ticket("小张");t1.start();t2.start();}
}import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class Ticket extends Thread{//100张电影票private static int count=100;public Ticket(){}public Ticket(String name){super(name);}//创建一个锁private static Lock lock=new ReentrantLock();@Overridepublic void run() {while(true){//上锁lock.lock();try {if(count<=10){System.out.println("不送啦");break;}else {Thread.sleep(30);count--;System.out.println(this.getName()+"送出一个礼物,还剩下"+count+"个礼物");}} catch (InterruptedException e) {throw new RuntimeException(e);} finally {//解锁lock.unlock();}}}
}

三、打印奇数数字


public class Main {public static void main(String[] args)  {//创建线程对象Ticket t1=new Ticket("计数器1:");Ticket t2=new Ticket("计数器2:");t1.start();t2.start();}
}import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class Ticket extends Thread{//100张电影票private static int count=1;public Ticket(){}public Ticket(String name){super(name);}//创建一个锁private static Lock lock=new ReentrantLock();@Overridepublic void run() {while(true){//上锁lock.lock();try {if(count>100){//超出100则停止break;}else {//未超出100,则继续Thread.sleep(10);if(IsJIShu(count))System.out.println(this.getName()+count+"是奇数");count++;}} catch (InterruptedException e) {throw new RuntimeException(e);} finally {//解锁lock.unlock();}}}public static boolean IsJIShu(int number){//判断奇数int count=0;for(int i=1;i<=Math.sqrt(number);i++){if((number%i)==0)count++;}if(count==1)return true;return false;}
}

四、抢红包


public class Main {public static void main(String[] args)  {//创建线程对象Player p1=new Player("玩家一");Player p2=new Player("玩家二");Player p3=new Player("玩家三");Player p4=new Player("玩家四");Player p5=new Player("玩家五");p1.start();p2.start();p3.start();p4.start();p5.start();}
}import java.util.Random;public class Player extends Thread{private String name;public static int Money=100;public static int count=3;public Player(){}public Player(String name){this.name = name;}@Overridepublic void run() {synchronized (Player.class){if (count > 0) {count--;Random r = new Random();if(count!=0){int mon = r.nextInt(Money) + 1;Money -= mon;System.out.println(this.name + "抢到了" + mon + "元红包");}else{int mon=Money;System.out.println(this.name + "抢到了" + mon + "元红包");}} else {System.out.println(this.name + "没有抢到红包");}}}
}

五、抽奖箱抽奖


public class Main {public static void main(String[] args)  {//创建线程对象Box box=new Box();Thread thread1=new Thread(box,"抽奖箱1");Thread thread2=new Thread(box,"抽奖箱2");thread2.start();thread1.start();}
}import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class Box implements Runnable {private static Lock lock=new ReentrantLock();private static ArrayList<Integer> list=new ArrayList<>();//静态代码块static {Collections.addAll(list,10,5,20,50,100,200,500,800,2,80,300,700);}@Overridepublic void run() {if(!list.isEmpty()){Thread thread=Thread.currentThread();while (true) {try {lock.lock();if (!list.isEmpty()) {int count = list.size();Random r = new Random();int index = r.nextInt(count);System.out.println(index);System.out.println(list.size());System.out.println(thread.getName() + "又产生了一个" + list.get(index) + "元大奖");list.remove(index);} else {break;}} catch (Exception e) {throw new RuntimeException(e);} finally {lock.unlock();}}}}
}

 六、抽奖箱进阶一


public class Main {public static void main(String[] args)  {//创建线程对象Box box1=new Box("抽奖箱一");Box box2=new Box("抽奖箱二");box2.start();box1.start();}
}import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class Box extends Thread{private static Lock lock=new ReentrantLock();private static ArrayList<Integer> list=new ArrayList<>();private String name;private int big=0;private int sum=0;public Box(){}public Box(String name){this.name=name;}private ArrayList<Integer> ownlist=new ArrayList<>();//静态代码块static {Collections.addAll(list,10,5,20,50,100,200,500,800,2,80,300,700);}@Overridepublic void run() {if(!list.isEmpty()){Thread thread=Thread.currentThread();while (true) {try {lock.lock();if (!list.isEmpty()) {int count = list.size();Random r = new Random();int index = r.nextInt(count);//将抽奖结果存入集合中,等最后打印this.ownlist.add(list.get(index));sum+=list.get(index);//当 big小于当前的抽奖结果时,将其赋值给bigthis.big=this.big<list.get(index)?list.get(index):this.big;//          System.out.println(thread.getName() + "又产生了一个" + list.get(index) + "元大奖");list.remove(index);} else {System.out.println("此次抽奖过程中,"+this.name+"总共产生了"+this.ownlist.size()+"个奖项");System.out.print("分别为:");for (Integer integer : this.ownlist) {System.out.print(" "+integer+",");}System.out.println("最高奖项为"+this.big+",总计为 "+this.sum+" 元");break;}} catch (Exception e) {throw new RuntimeException(e);} finally {lock.unlock();}}}}
}

 七、抽奖箱进阶二

 


public class Main {public static void main(String[] args)  {//创建线程对象Box box1=new Box("抽奖箱一");Box box2=new Box("抽奖箱二");box2.start();box1.start();}
}import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class Box extends Thread{private static Lock lock=new ReentrantLock();private static ArrayList<Integer> list=new ArrayList<>();private static int count=0;private static ArrayList<String> biglist=new ArrayList<>();private String name;private int big=0;private int sum=0;public Box(){}public Box(String name){this.name=name;}private ArrayList<Integer> ownlist=new ArrayList<>();//静态代码块static {Collections.addAll(list,10,5,20,50,100,200,500,800,2,80,300,700);}@Overridepublic void run() {if(!list.isEmpty()){Thread thread=Thread.currentThread();while (true) {try {lock.lock();if (!list.isEmpty()) {int count = list.size();Random r = new Random();int index = r.nextInt(count);//将抽奖结果存入集合中,等最后打印this.ownlist.add(list.get(index));sum+=list.get(index);//当 big小于当前的抽奖结果时,将其赋值给bigthis.big=this.big<list.get(index)?list.get(index):this.big;//          System.out.println(thread.getName() + "又产生了一个" + list.get(index) + "元大奖");list.remove(index);Thread.yield();} else {System.out.println("此次抽奖过程中,"+this.name+"总共产生了"+this.ownlist.size()+"个奖项");System.out.print("分别为:");for (Integer integer : this.ownlist) {System.out.print(" "+integer+",");}System.out.println("最高奖项为"+this.big+",总计为 "+this.sum+" 元");count++;biglist.add(this.name+","+this.big);break;}} catch (Exception e) {throw new RuntimeException(e);} finally {lock.unlock();}}if(count==2){if(Integer.parseInt(biglist.get(0).split(",")[1])>Integer.parseInt(biglist.get(1).split(",")[1])){System.out.println("在此次抽奖过程中,"+biglist.get(0).split(",")[0]+"产生了最大奖项,金额为"+Integer.parseInt(biglist.get(0).split(",")[1])+"元");}else{System.out.println("在此次抽奖过程中,"+biglist.get(1).split(",")[0]+"产生了最大奖项,金额为"+Integer.parseInt(biglist.get(1).split(",")[1])+"元");}}}}
}

另一种方法: 

 

原理: 

每个线程的run方法只会执行一次,run方法中的方法体,会在线程争夺到CPU使用权后进行。


http://www.ppmy.cn/news/1555507.html

相关文章

设计模式详解(十):策略模式——Strategy

什么是Strategy设计模式&#xff1f; Strategy模式是一种行为型设计模式&#xff0c;它定义了一系列算法&#xff0c;将每种算法封装到独立的类中&#xff0c;使它们可以互换。使用该模式&#xff0c;可以在不修改客户端代码的情况下动态地改变算法的行为。 为什么需要Strate…

【LeetCode】3356、零数组变换 II

【LeetCode】3356、零数组变换 II 文章目录 一、数据结构-差分-一维差分、二分1.1 数据结构-差分-一维差分、二分1.1.1 题意复述1.1.2 思路1.1.3 手写二分1.1.4 sort.Search() 二分1.1.5 sort.Find() 二分 二、多语言解法 一、数据结构-差分-一维差分、二分 1.1 数据结构-差分…

第二部分:Linux软件部署

注意&#xff1a;安装操作需要root权限1.MySQL数据库管理系统安装[单机软件] MySQL的安装操可以通过前面学习的yum命令进行。1.1 MySQL5.7在CentOS版本 安装 1. 配置yum仓库 #更新密钥&#xff08;导入yum仓库需要的密钥&#xff09;rpm --import https://repo.mysql.com/RPM…

【077】基于51单片机智能消毒柜【Proteus仿真+Keil程序+报告+原理图】

☆、设计硬件组成&#xff1a;51单片机最小系统DHT11温湿度传感器LCD1602液晶显示AT24C02存储芯片紫外线灯继电器按键设置限位开关蜂鸣器LED灯。 1、设计采用STC89C51/52、AT89C51/52、AT89S51/52作为主控芯片&#xff1b; 2、采用DHT11温湿度传感器实时检测温湿度数值&#…

数字证书管理工具 openssl keytool

OPENSSL 命令 openssl command [ command_opts ] [ command_args ] 常用command: version 用于查看版本信息 enc 用于加解密 ciphers 列出加密套件 genrsa 用于生成私钥 -des|-des3|-idea&#xff1a;用来加密私钥文件的三种对称加密算法。 rsa …

在 React 中,创建和嵌套组件、添加标签和样式、显示数据、渲染条件和列表、对事件做出响应并更新界面以及在组件间共享数据是常见的任务

文章目录 1. 创建和嵌套组件创建组件嵌套组件 2. 添加标签和样式添加标签添加样式 3. 显示数据显示静态数据显示动态数据 4. 渲染条件和列表条件渲染列表渲染 5. 对事件做出响应并更新界面处理事件 6. 在组件间共享数据使用 Context API react 如何创建和嵌套组件 如何添加标签…

【LC】231. 2 的幂

题目描述: 给你一个整数 n&#xff0c;请你判断该整数是否是 2 的幂次方。如果是&#xff0c;返回 true &#xff1b;否则&#xff0c;返回 false 。 如果存在一个整数 x 使得 n 2x &#xff0c;则认为 n 是 2 的幂次方。 示例 1&#xff1a; 输入&#xff1a;n 1 输出&a…

从2D到3D:解锁视频中的隐形魔法世界

点击访问 chatTools 免费体验GPT最新模型&#xff0c;包括o1推理模型、GPT4o 和Claude等模型&#xff01; ## 技术革命&#xff1a;普通视频中的惊人秘密 在数字技术日新月异的今天&#xff0c;3D建模和虚拟现实领域一直存在着巨大的挑战。传统的3D数据获取方式不仅耗时耗力&a…