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 prs08;
- import java.util.Scanner;
- class Bufor
- {
- final int roz=100000;
- long Bufor[]=new long[roz];
- 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,t1;
- static void rozgrzewka(int rmp,int rmk,int ile)
- {
- t0=System.currentTimeMillis();
- t1=t0+1000;
- buf.mp=rmp;
- buf.mk=rmk;
- buf.zapas=ile;
- }
- synchronized void producent()
- {
- long nr;
- if (buf.zapas<buf.roz-1){
- nr=(long)Math.round(Math.random()*100000);
- try {
- int czas=(int)Math.round(Math.random()*3);
- sleep(czas);
- }
- catch (Exception E)
- { System.out.println("Wyjatek;"+ E);
- }
- buf.Bufor[buf.mp] = nr;
- buf.mp = (buf.mp+1)%buf.roz;
- if (buf.mp > buf.mk){
- buf.zapas = buf.mp - buf.mk;
- }else{
- buf.zapas = (buf.zapas+1)%buf.roz;
- }
- }
- }
- synchronized void konsument(){
- long konsumpcja;
- if (buf.zapas>0){
- konsumpcja = buf.Bufor[buf.mp];
- buf.mk = (buf.mk+1)%buf.roz;
- buf.zapas--;
- try{
- long czas= (long)Math.round(Math.random()*9);
- sleep(czas);
- } catch (Exception E) {
- System.out.println("blad; "+ E);
- }
- }
- }
- public void run()
- {
- long tx= System.currentTimeMillis();
- while (tx<t0+100)
- if (nr<10){
- producent();
- }else{
- konsument();
- }
- raport();
- tx=System.currentTimeMillis();
- }void raport(){
- if(nr<10){
- System.out.println("Produkcja - "+this.getName() );
- }else{
- System.out.println("Konsumpcja - "+this.getName());
- }
- }}
- /**
- *
- * @author Student
- */
- public class PRS08 {
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- ProdKons P[]= new ProdKons[10];
- ProdKons K[]= new ProdKons[1000];
- ProdKons.rozgrzewka(0,0,0);
- {
- for(int i=0; i<10;i++){
- P[i]= new ProdKons(i);
- }
- for (int i =0;i<1000;i++){
- K[i] = new ProdKons(i+10);
- }
- for(int i=0;i<10;i++){
- P[i].start();
- }
- for(int i=0;i<1000;i++){
- K[i].start();
- }
- for(int i=0;i<100;)
- try{
- P[i].join();
- }catch(InterruptedException E){
- System.out.println("W: "+E);
- }
- }
- // TODO code application logic here
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement