Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package javaapplication1;
- import java.util.Arrays;
- import java.util.Random;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- public class JavaApplication1 {
- static Thread prod , cons;
- static int[] arr = new int[10];
- static int bufferSize = arr.length;
- static int pos=0;
- static int full=0; // number of slots full
- static int empty=bufferSize; // number of slots empty
- static boolean entry = false;
- public static void main(String[] args) {
- producer();
- cons();
- }
- public static void cons(){
- prod = new Thread(new Runnable() {
- @Override
- public void run() {
- for(int i=0; i<bufferSize; i++){
- if(entry==true){
- try {
- Thread.sleep(200);
- } catch (InterruptedException ex) {
- Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- if(entry==false){
- full--;
- entry=true;
- System.out.println("Consumer working on index "+ i);
- arr[i] = 0;
- System.out.println(Arrays.toString(arr));
- entry = false;
- empty++;
- }
- }
- }
- });
- prod.start();
- }
- public static void producer(){
- Random ran = new Random();
- cons = new Thread(new Runnable() {
- @Override
- public void run() {
- for(int i=0; i<bufferSize; i++){
- if(entry==true){
- try {
- Thread.sleep(200);
- } catch (InterruptedException ex) {
- Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- if(entry==false){
- int item = ran.nextInt(100);
- empty--;
- entry=true;
- System.out.println("Producer working on index "+ i);
- arr[i] = item;
- System.out.println(Arrays.toString(arr));
- entry = false;
- full++;
- }
- }
- }
- });
- cons.start();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement