1.模拟多个人进山洞情景
问题描述:模拟多个人通过一个山洞的场景。这个山洞每次只能通过一个人,每个人通过山洞的时间为5秒,有10个人同时准备过此山洞,显示每次通过山洞的人的姓名和顺序。
ThroughCave类:
public class ThroughCave {
private String name[];
public ThroughCave() {
String name[] = {
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};
this.name = name;
}
public void PrintName(String name) {
synchronized ("") {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(name + "通过了山洞");
}
public void SendAllName() {
for (int i = 0; i < name.length; i++) {
GetNameThread gt = new GetNameThread(this, name[i]);
Thread thread = new Thread(gt);
thread.start();
}
}
public static void main(String[] args) {
ThroughCave tc = new ThroughCave();
tc.SendAllName();
}
}
GetNameThread类:
public class GetNameThread implements Runnable {
private ThroughCave tcave;
private String name;
public GetNameThread(ThroughCave tcave, String name) {
this.tcave = tcave;
this.name = name;
}
@Override
public void run() {
tcave.PrintName(name);
}
}
2.生产者消费者模型
Product类:
public class Product {
private String name;
public Product(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
ProductPool类:
public class ProductPool {
public int maxSize = 0;
public List<Product> productList;
public ProductPool(int maxSize, List<Product> productList) {
this.maxSize = maxSize;
this.productList = productList;
}
public synchronized void push(Product product) {
if (this.productList.size() == this.maxSize) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.productList.add(product);
this.notifyAll();
}
public synchronized Product pop() {
if (this.productList.size() == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Product product = this.productList.remove(0);
this.notifyAll();
return product;
}
}
Producter类:
public class Producter implements Runnable {
private ProductPool productPool;
public Producter(ProductPool productPool) {
this.productPool = productPool;
}
@Override
public void run() {
int i = 1;
while (true) {
String name = "产品" + i++;
Product product = new Product(name);
this.productPool.push(product);
System.out.println("生产了:" + name);
}
}
}
Consumer类:
public class Consumer implements Runnable {
private ProductPool productPool;
public Consumer(ProductPool productPool) {
this.productPool = productPool;
}
@Override
public void run() {
while (true) {
Product product = this.productPool.pop();
System.out.println("消费了:" + product.getName());
}
}
}
mainMethod类:
import java.util.LinkedList;
public class mainMethod {
public static void main(String[] args) {
ProductPool productPool = new ProductPool(7, new LinkedList<Product>());
Producter producter = new Producter(productPool);
Thread thread1 = new Thread(producter);
Consumer consumer = new Consumer(productPool);
Thread thread2 = new Thread(consumer);
thread1.start();
thread2.start();
}
}