某次面试阿里云,要求实时写一个小程序,要求如下:
1.两个线程,一个线程生产者,一个线程是消费者
2.生产者生产票,超过10张就休息,被消费了就继续生产。
3.消费者消费票,票没了之后就休息,有票了接着消费。
题目看着很简单,但却包含了很多考点:消息队列、线程、线程通信、锁。
具体看看我写的源码,这是后期几经修改后的内容。
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* 某次面试阿里云,要求实时写一个小程序,要求如下:
* 1.两个线程,一个线程生产者,一个线程是消费者
* 2.生产者生产票,超过10张就休息,被消费了就继续生产。
* 3.消费者消费票,票没了之后就休息,有票了接着消费。
* 题目看着很简单,但却包含了很多考点:消息队列、线程、线程通信、锁。
* 具体看看我写的源码,这是后期几经修改后的内容。
*/
public class Test {
private static Queue queue = new ConcurrentLinkedQueue();
private static Object lock = new Object();
public static void main(String[] args) {
//生产者线程
Thread p = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
queue.add("piao");
System.out.println(Thread.currentThread().getName() + ":加票...余票有" + queue.size() + "张");
synchronized (lock) {
//每次生产完了之后通知一下等待中的消费者
lock.notify();
if (queue.size() >= 10) {
System.out.println(Thread.currentThread().getName() + ":票加满了");
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "Provider");
Thread c = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
String ticket = (String) queue.poll();
System.out.println(Thread.currentThread().getName() + ":取票...余票有" + queue.size() + "张");
try {
Thread.sleep(500L);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock) {
//每次消费完了之后通知一下等待中的生产者
lock.notify();
if (ticket == null) {
System.out.println(Thread.currentThread().getName() + ":票没有了");
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}, "Comsumer");
p.start();
try {
Thread.sleep(300L);
} catch (InterruptedException e) {
e.printStackTrace();
}
c.start();
}
}