Advertisement
Guest User

Apple Farmers

a guest
Aug 2nd, 2019
330
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.59 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.List;
  4.  
  5. class Main {
  6.     public static void main(String[] args) throws Exception {
  7.         System.out.println("Hello world!");
  8.  
  9.         List<Apple> apples = Collections.synchronizedList(new ArrayList<>());
  10.  
  11.         Thread t1 = new Thread(new Farmer(apples));
  12.         t1.start();
  13.  
  14.         Thread t2 = new Thread(new Farmer(apples));
  15.         t2.start();
  16.  
  17.         while (apples.size() == 0) {
  18.             // System.out.println(apples.size());
  19.         }
  20.  
  21.         System.out.println(apples.size() + " main ended");
  22.     }
  23. }
  24.  
  25. ________________________________________________________________________________
  26.  
  27. import java.util.*;
  28.  
  29. public class Farmer implements Runnable {
  30.     List<Apple> busket;
  31.     private static int count;
  32.     private int id;
  33.     private int appleCount;
  34.  
  35.     public Farmer(List<Apple> busket) {
  36.         this.busket = busket;
  37.         id = count++;
  38.     }
  39.  
  40.     public void makeApple() {
  41.         Apple apple = new Apple("Apple" + appleCount + " by Farmer" + id);
  42.         System.out.println("making apple: " + apple);
  43.  
  44.         busket.add(apple);
  45.         appleCount++;
  46.     }
  47.  
  48.     public void run() {
  49.         while (appleCount < 5) {
  50.             makeApple();
  51.         }
  52.     }
  53. }
  54.  
  55. ________________________________________________________________________
  56.  
  57. public class Apple {
  58.     private String name;
  59.  
  60.     public String getName() {
  61.         return name;
  62.     }
  63.  
  64.     public String toString() {
  65.         return name;
  66.     }
  67.  
  68.     public Apple(String name) {
  69.         this.name = name;
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement