/*
* 实现Runnable接口
*/
public class T1 implements Runnable {
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("thread=" + i);
}
}
}
public static void main(String[] args) {
T1 t1 = new T1();
Thread thread = new Thread(t1);
thread.start();
for (int i = 0; i < 1000; i++) {
System.out.println("main===========" + i);
}
}
/*
* 继承Thread类
*/
public class T3 extends Thread {
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("thread=" + i);
}
}
}
public static void main(String[] args) {
T3 t3 = new T3();
t3.start();
for (int i = 0; i < 1000; i++) {
System.out.println("main*************" + i);
}
}
/*
经典的生产者消费者问题(模拟做馒头和吃馒头)
*/
/*
* 馒头
*/
public class WoTou {
private int id;
public WoTou(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
/*
* 装馒头的篮子
*/
public class LanZi {
private int index = 0;
private WoTou[] arrWT = new WoTou[10];
/*
* 放馒头
*/
public synchronized void push(WoTou wt) {
while (index == arrWT.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
arrWT[index] = wt;
index++;
}
/*
* 拿馒头
*/
public synchronized WoTou pop() {
while (index == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
index--;
return arrWT[index];
}
}
/*
* 生产者
*/
public class Producer implements Runnable {
private LanZi lanZi = null;
public Producer(LanZi lanZi) {
this.lanZi = lanZi;
}
/*
* 生产
*/
public void run() {
for (int i = 0; i < 20; i++) {
WoTou wt = new WoTou(i);
lanZi.push(wt);
System.out.println("***生产了:" + wt.getId());
try {
Thread.sleep((int) (Math.random() * 600));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/*
* 消费者
*/
public class Consumer implements Runnable {
private LanZi lanZi = null;
public Consumer(LanZi lanZi) {
this.lanZi = lanZi;
}
/*
* 消费
*/
public void run() {
for (int i = 0; i < 20; i++) {
WoTou wt = lanZi.pop();
System.out.println("---消费了:" + wt.getId());
try {
Thread.sleep((int) (Math.random() * 800));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class T {
/*
* 测试类
*/
public static void main(String[] args) {
LanZi lanZi = new LanZi();
Producer p = new Producer(lanZi);
Consumer c = new Consumer(lanZi);
new Thread(p).start();
new Thread(c).start();
}
}