Last active
January 16, 2020 08:22
-
-
Save xialeistudio/a0c72516b7c3820dcfda5ac433633ed8 to your computer and use it in GitHub Desktop.
ProducerConsumer.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.xialei.learn.concurrent; | |
import java.util.ArrayList; | |
import java.util.Date; | |
import java.util.List; | |
// 生产者消费者例子 | |
public class Main { | |
public static void main(String[] args) { | |
List<String> queue = new ArrayList<>(); | |
Consumer consumer = new Consumer(queue); | |
Producer producer = new Producer(queue); | |
new Thread(consumer).start(); | |
new Thread(producer).start(); | |
} | |
// 生产者 | |
public static class Producer implements Runnable { | |
private final List<String> queue; | |
Producer(List<String> queue) { | |
this.queue = queue; | |
} | |
@Override | |
public void run() { | |
try { | |
while (true) { | |
Thread.sleep(2000); | |
synchronized (queue) { | |
queue.add(new Date().toString()); | |
queue.notify(); | |
} | |
} | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
// 消费者 | |
public static class Consumer implements Runnable { | |
private final List<String> queue; | |
Consumer(List<String> queue) { | |
this.queue = queue; | |
} | |
@Override | |
public void run() { | |
while (true) { | |
synchronized (queue) { | |
if (queue.size() == 0) { | |
try { | |
queue.wait(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
System.out.println(queue.remove(0)); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment