Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package pr4;
- import java.util.Scanner;
- /**
- *
- * @author student
- */
- class Bufor
- {
- final int rozmiar=10000;
- long bufor[]=new long[rozmiar];
- int mp, mk, zapas;
- }
- class ProdKons extends Thread
- {
- int nr;
- public ProdKons(int nr)
- {
- this.nr=nr;
- if(nr<20)
- this.setName("Producent:"+nr);
- else
- this.setName("Konsument:"+nr);
- }
- static Bufor buf=new Bufor();
- static long t0;
- static void rozgrzewka(int pmp, int pmk, int pzapas)
- {
- buf.mp=pmp;
- buf.mk=pmk;
- buf.zapas=pzapas;
- t0=System.currentTimeMillis();
- }
- synchronized void producent()
- {
- if(buf.zapas<buf.rozmiar)
- {long czas=(long)Math.round(Math.random()*2);
- try
- {this.sleep(czas+5);}
- catch(Exception e){System.out.print(" wyjątek - "+e);}
- }
- long nr=(long)Math.round(Math.random()*100000);
- buf.bufor[buf.mp]=nr;
- buf.mp=(buf.mp+1)%buf.rozmiar;
- buf.zapas++;
- }
- synchronized void konsument()
- {
- if(buf.zapas>0)
- {
- long konsumcja=buf.bufor[buf.mk];
- buf.mk=(buf.mk+1)%buf.rozmiar;
- buf.zapas--;
- long czas=(long)(5+Math.round(Math.random()*10));
- try
- {
- sleep(czas);
- }
- catch(Exception E){System.out.print(E);}
- }
- }
- public void run()
- {
- long tx=t0;
- while(tx<t0+10000)
- {
- if(nr<20)producent();
- else konsument();
- tx=System.currentTimeMillis();
- raport();
- }
- }
- void raport()
- {
- if(nr<20)
- System.out.println("Produkcja : "+this.getName());
- else
- System.out.println("Konsumpcja : "+this.getName());
- }
- }
- public class Pr4 {
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- ProdKons.rozgrzewka(0, 0, 0);
- ProdKons P[]=new ProdKons[20];
- ProdKons K[]=new ProdKons[1000];
- for(int i=0; i<20; i++)P[i]=new ProdKons(i);
- for(int i=0; i<1000; i++)K[i]=new ProdKons(i+20);
- for(int i=0; i<20; i++)P[i].start();
- //for(int i=0; i<1000; i++)K[i].start();
- for(int i=0; i<20; i++)
- try
- {
- P[i].join();
- }
- catch(InterruptedExpection e){System.out.printf(e);}
- /*for(int i=0; i<1000; i++)
- try
- {
- K[i].join();
- }
- catch(InterruptedExpection e){System.out.printf(e);}*/
- // TODO code application logic here
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement