1.线程/进程的概念
2.创建和启动线程的方式
3常用方法:
sleep()
jion()
yield()
wait()
notify()
notifyAll()
4.synchronized
/**
* 生产者消费者(以生产汽车 ,销售汽车为例)
*
* @author Solarisy
*
*/
public class TestProducerConsumer {
public static void main(String[] args) {
WareHouse wh = new WareHouse();
Producer per = new Producer(wh);
Consumer cer = new Consumer(wh);
new Thread(per).start();
new Thread(cer).start();
}
}
/**
* 汽车
*
* @author Solarisy
*
*/
class Car {
/* 汽车编号 */
private int id;
Car(int id) {
this.id = id;
}
public String toString() {
return "" + id;
}
}
/**
* 大商店
*
* @author Administrator
*
*/
class WareHouse {
/* 存放汽车的车库 */
Car[] carport = new Car[6];
/* 车位号 */
int index;
/**
* 生产一辆汽车,将汽车停入车位
* 同步方法
*
* @param car
*/
public synchronized void in(Car car) throws Exception {
while (index == 6) {
System.out.println("车位满了,生产等待中......");
this.wait();
}
carport[index] = car;
System.out.println("The car was produce that id is :" + car
+ " 放入车位 = " + index);
this.notify();
index++;
}
/**
* 销售一辆汽车,将汽车开车车位
* 同步方法
*
*/
public synchronized Car out() throws Exception {
while (index <= 0) {
System.out.println("车库空了。‘有钱竟然买不到汽车,我回家等着......’");
this.wait();
}
index--;
System.out.println( carport[index] + "号汽车被顾客买走了...");
this.notify();
return carport[index];
}
}
/**
* 生产者
*
* @author Solarisy
*
*/
class Producer implements Runnable {
WareHouse wh;
Producer(WareHouse wh) {
this.wh = wh;
}
/* 生产汽车 */
public void produce() throws Exception {
for (int i = 0; i < 20; i++) {
Car car = new Car(i);
wh.in(car);
}
}
public void run() {
try {
produce();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 消费者
*
* @author Solarisy
*
*/
class Consumer implements Runnable {
WareHouse wh;
Consumer(WareHouse wh) {
this.wh = wh;
}
/* 买车 */
public void buy() throws Exception {
for (int i = 0; i < 20; i++) {
wh.out();
}
}
public void run() {
try {
buy();
} catch (Exception e) {
e.printStackTrace();
}
}
}