java多线程对生产者消费者模式的简单应用

1、多线程是java学习中很重要的类容,一定要多理解并实践
2、生产者消费者的思想是:只有当生产者生产出产品时,消费者才能进行消费,否则只能等待生产者生产出产品后才能消费;这就需要用到线程之间的通信来控制。
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class ThreadTest {
public static void main(String[] args) {
Publisher publisher = new Publisher();
new ProduceThread(“生产者1”, publisher).start();
new ConsumeThread(“消费者1”, publisher).start();
new ProduceThread(“生产者2”, publisher).start();
new ConsumeThread(“消费者2”, publisher).start();
}
}

class ProduceThread extends Thread {
private Publisher publisher;
public ProduceThread(String name, Publisher publisher) {
super(name);
this.publisher = publisher;
}

@Override
public void run() {
    try {
        publisher.produce();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

}

class ConsumeThread extends Thread {
private Publisher publisher;
public ConsumeThread(String name, Publisher publisher) {
super(name);
this.publisher = publisher;
}

@Override
public void run() {
    try {
        publisher.consume();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

}

enum Lock {
x
}

class Publisher {
private List list = new ArrayList();
private static final String[] BOOKS = {“java”, “c++”, “Scala”, “R”};
public void produce() throws InterruptedException {
while (true) {
synchronized (Lock.x) {
if (!list.isEmpty()) {
try {
Lock.x.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
Random random = new Random();
int anInt = random.nextInt(BOOKS.length);
String bookName = BOOKS[anInt];
Book book = new Book(bookName);
list.add(book);
String currentThreadName = Thread.currentThread().getName();
System.out.println(currentThreadName + “印刷了” + list);
Thread.sleep(200);
Lock.x.notifyAll();
}
}
}
}

public void consume() throws InterruptedException {
    while (true) {
        synchronized (Lock.x) {
            if (list.isEmpty()) {
                try {
                    Lock.x.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                Book book = list.get(0);
                String currentThreadName = Thread.currentThread().getName();
                System.out.println(currentThreadName + "买了" + book);
                list.remove(0);
                Thread.sleep(200);
                Lock.x.notifyAll();
            }
        }
    }
}

}

class Book {
String name;
public Book(String anme) {
this.name = anme;
}
public Book() {

}
public String getAnme() {
    return name;
}
public void setAnme(String anme) {
    this.name = anme;
}
@Override
public String toString() {
    return "Book{" +
            "anme='" + name + '\'' +
            '}';
}

}

上一篇:Django---简易图书管理系统(B/S架构)


下一篇:Django/DRF序列化