黑马程序员技术交流社区
标题:
40个线程同时跑起和谐操作4个类的4个对象
[打印本页]
作者:
slatop@qq.com
时间:
2013-6-13 17:15
标题:
40个线程同时跑起和谐操作4个类的4个对象
好TM难写。花了半天的时间。能把这个看懂基本你多线程没问题了。太累了很多地方没加注释
package com.heima.Demo;
public class Demo{
public static void main(String[] args) throws InterruptedException {
//创建描述动物行为的对象
AnimalDescribe animal = new AnimalDescribe();
//鸟类与鱼类分两个线程循环向动物描述对象中添加描述信息
Fish fish = new Fish(animal);
Bird brid = new Bird(animal);
Beast beast = new Beast(animal);
for (int i = 0; i <= 10; i++) {
new Thread(fish).start();
new Thread(brid).start();
new Thread(beast).start();
new Thread(animal).start();
}
animal.flag = 1;
synchronized (animal) {
animal.notifyAll();
}
}
}
//动物描述类,主要用来描述一个类动物的行为
class AnimalDescribe implements Runnable{
int flag = 100;
private int runCount = 45;
private String typeName;//动物的种类
private String action; //动物的行为
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
//打印当前动物的种类和对应的行为
public synchronized void print(){
try {
while (flag != 0) wait();
System.out.println(Thread.currentThread().getName() + "\t--显示--" + typeName + ":" + action);
if (typeName.equals("鸟")) {
flag = 2;
}
else if (typeName.equals("鱼")) {
flag = 3;
}
else if (typeName.equals("兽")) {
flag = 1;
}
notifyAll();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
print();
}
}
}
abstract class Animal implements Runnable {
public AnimalDescribe animal = null;//保存一个动物描述对象
public int runCount = 15;
public Animal(AnimalDescribe animal) {
this.animal = animal;
}
public void addData(int index, String typeName, String action){
try {
while (animal.flag != index) animal.wait();
animal.setTypeName(typeName);
animal.setAction(action);
System.out.println(Thread.currentThread().getName() + "\t-添加数据完成!");
animal.flag = 0;
animal.notifyAll();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//鸟类
class Bird extends Animal {
public Bird(AnimalDescribe animal) {
super(animal);
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
synchronized (animal) {
addData(1, "鸟", "在天上飞!");
}
}
}
}
//鱼类
class Fish extends Animal {
public Fish(AnimalDescribe animal) {
super(animal);
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
synchronized (animal) {
addData(2, "鱼", "在水里游!");
}
}
}
}
//兽类
class Beast extends Animal {
public Beast(AnimalDescribe animal) {
super(animal);
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
synchronized (animal) {
addData(3, "兽", "在地上跑!");
}
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2