package ThreadTest.Day3;
public class Test06 {
public static void main(String[] args) {
Container container =new Container();
new Thread(new product(container)).start();
new Thread(new consumer(container)).start();
}
}
class Chicken{
int id;
public Chicken(int id) {
this.id = id;
}
}
class Container{
Chicken [] chickens =new Chicken[10];
int count =0;
public synchronized void push(Chicken chicken) throws InterruptedException {
if (count ==chickens.length){
this.wait();
}
chickens[count] =chicken;
count++;
this.notifyAll();
}
public synchronized void pop() throws InterruptedException {
if (count ==0){
this.wait();
}
count--;
System.out.println("消费了第"+chickens[count].id+"只鸡");
this.notifyAll();
}
}
class product implements Runnable{
Container container;
public product(Container container) {
this.container = container;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
try {
container.push(new Chicken(i));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("生产了第"+i+"只鸡");
}
}
}
class consumer implements Runnable{
Container container;
public consumer(Container container) {
this.container = container;
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 1; i <= 100; i++) {
try {
container.pop();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package ThreadTest.Day3;
public class Test07 {
public static void main(String[] args) {
Tv tv =new Tv();
new Thread(new player(tv)).start();
new Thread(new watcher(tv)).start();
}
}
class Tv{
boolean flag =true;
String name;
public synchronized void play(String name) throws InterruptedException {
if (!flag){
this.wait();
}
System.out.println("演员表演了:"+name);
this.name =name;
this.notifyAll();
this.flag =!this.flag;
}
public synchronized void watch() throws InterruptedException {
if (flag){
this.wait();
}
System.out.println("观众观看了:"+name);
this.flag =!this.flag;
this.notifyAll();
}
}
class player implements Runnable{
Tv tv;
public player(Tv tv) {
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i%2==0) {
try {
this.tv.play("快乐大本营");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else {
try {
this.tv.play("抖音,记录美好生活");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class watcher implements Runnable{
Tv tv;
public watcher(Tv tv) {
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
tv.watch();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}