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 = 100;
- long bufor[] = new long[rozmiar];
- int mp, mk, zapas;
- }
- class ProdKons extends Thread
- {
- int nr;
- public ProdKons(int nr)
- {
- this.nr=nr;
- if(nr<10)
- 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(3);}
- catch (Exception e) {System.out.print("wyjątek -"+e);}
- }
- 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<100)
- {
- if (nr<10) 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[10];
- ProdKons K[]= new ProdKons[100];
- for (int i=0; i<10; i++)P[i]= new ProdKons(i);
- for (int i=0; i<10; i++)P[i].start();
- for (int i=0; i<100; i++)K[i]= new ProdKons(i+20);
- for (int i=0; i<100; i++)K[i].start();
- for (int i=0; i<10; i++)
- try{
- P[i].join();
- }
- catch(InterruptedException e){System.out.println(e);}
- for (int i=0; i<100; i++)
- try
- {
- K[i].join();
- }
- catch(InterruptedException e) {System.out.println(e);}
- // TODO code application logic here
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement