概述
1、synchronized同步代码块
package com.dhu.thread.cinema;
class Cinema{
private int available; //可选的座位
private String name; //影院名
public Cinema(int available, String name) {
this.available = available;
this.name = name;
}
public int getAvailable() {
return available;
}
public void setAvailable(int available) {
this.available = available;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean bookTicket(int seats) {
System.out.println("可用位置: " + available);
if(this.available < seats) {
return false;
}
this.available -= seats;
return true;
}
}class Customer implements Runnable{
private Cinema cinema;
private int seats; //订的位置
public Customer(Cinema cinema, int seats) {
this.cinema = cinema;
this.seats = seats;
}@Override
public void run() {
synchronized(cinema) {
if(cinema.bookTicket(seats)) {
System.out.println("出票成功," + Thread.currentThread().getName() + "购票位置为: " + seats);
}else {
System.out.println("出票失败," + Thread.currentThread().getName() + "位置不够");
}
}
}
}public class HappyCinema {
public static void main(String[] args) {
Cinema c1 = new Cinema(3, "DHU影院");
new Thread(new Customer(c1, 2), "老高").start();
new Thread(new Customer(c1, 1), "小米").start();
}}
2、加入容器操作
package com.dhu.thread.cinema;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class DHUCinema{
private List<Integer> available; //可选的座位
private String name; //影院名
public DHUCinema(List<Integer> available, String name) {
this.available = available;
this.name = name;
}
public boolean bookTicket(List<Integer> seats) { 订票的位置
System.out.println("可用位置: " + this.available);
//两个容器的比较
List<Integer> available_copy = new ArrayList<>();
available_copy.addAll(available);
//容器相减
available_copy.removeAll(seats);
if(available.size() - available_copy.size() == seats.size()) {
available = available_copy; //更新剩余的可选座位
return true;
}
return false;
}
}
class UCustomer implements Runnable{
private DHUCinema cinema;
private List<Integer> seats; //订的位置
public UCustomer(DHUCinema cinema, List<Integer> seats) {
this.cinema = cinema;
this.seats = seats;
}
@Override
public void run() {
synchronized(cinema) {
if(cinema.bookTicket(seats)) {
System.out.println("出票成功," + Thread.currentThread().getName() + "购票位置为: " + seats);
}else {
System.out.println("出票失败," + Thread.currentThread().getName() + "位置不够");
}
}
}
}
public class HappyCinema02 {
public static void main(String[] args) {
List<Integer> available = new ArrayList<>(Arrays.asList(1,2,3,4,6,7));
List<Integer> seats1 = new ArrayList<>(Arrays.asList(1,2));
List<Integer> seats2 = new ArrayList<>(Arrays.asList(3,4,8));
DHUCinema cinema = new DHUCinema(available, "DHU影院");
new Thread(new UCustomer(cinema, seats1), "老王").start();
new Thread(new UCustomer(cinema, seats2), "小米").start();
}
}
运行结果:
最后
以上就是微笑书本为你收集整理的多线程 -- 容器之间的并发操作的全部内容,希望文章能够帮你解决多线程 -- 容器之间的并发操作所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复