新手上路,请各位前辈,多多包含。
用生活里的场景做一个简单的描述吧:假设一个影院有三个售票口,分别用于向儿童、成人和老人售票。影院为每个窗口放有100张电影票,分别是儿童票、成人票和老人票。三个窗口需要同时卖票,而现在只有一个售票员,这个售票员就相当于一个CPU,三个窗口就相当于三个线程。只要记住门只有一个,每次只能一个人进,有很多人需要从这里进入,你只要维持好顺序就行了。下面做一个简单的事例
在java中实现线程,有两种方式。
继承Thread类派生一个新的线程类,重载它的run()方法。
实现Runnalbe接口,重载Runnalbe接口中的run()方法。
package com.demo.pc;
/**
* 消费者
* @author Administrator
*
*/
public class Consumer implements Runnable{
private Stock<String> stock;
public Consumer(Stock<String> stock) {
this.stock=stock;
}
public void run() {
for (int i = 1; i < 11; i++) {
System.out.println("消费:"+stock.popUp());
}
}
}
package com.demo.pc;
/**
* 生产者
* @author Administrator
*
*/
public class Producer implements Runnable{
private Stock<String> stock;
public Producer(Stock<String> stock) {
this.stock=stock;
}
public void run() {
for (int i = 1; i < 11; i++) {
stock.push("第"+i+"元素");
System.out.println("生产:第"+i+"元素");
}
}
}
package com.demo.pc;
import java.util.ArrayList;
import java.util.List;
public class Stock<E> {
private List<E> list;
private int size;
public Stock() {
list=new ArrayList<E>();
size=0;
}
//压栈
public synchronized void push(E arg){
list.add(arg);
size++;
//唤醒
notify();
}
//弹栈
public synchronized E popUp(){
while(size<1){
try {
//等待
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return list.remove(--size);
}
}
package com.demo.pc;
public class Test {
public static void main(String[] args) {
Stock<String> stock=new Stock<String>();
Thread tp=new Thread(new Producer(stock));
Thread tc=new Thread(new Consumer(stock));
tp.start();
tc.start();
}
}