/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package prodkonslosn; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Administrator */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Produkt p = new Produkt(); new Thread(new Producent(p)).start(); new Thread(new Konsument(p)).start(); } } //En struktur som definierar en "produkt" som skall delas mellan två trådar class Produkt { private int slumptal; boolean tom = true; synchronized public int hamta() { while(tom) { try { wait(); } catch (InterruptedException ex) {} } tom = true; notifyAll(); return slumptal; } synchronized public void spara(int tal) { while(!tom) { try { wait(); } catch (InterruptedException ex) {} } slumptal = tal; tom = false; notifyAll(); } } //innehåller funktioner för en "producent" som skall producera "slumptal" en gång/sec class Producent implements Runnable { Produkt p; public Producent(Produkt prod) { p = prod; } public void run() { while(true) { Random r = new Random(); int slump = r.nextInt(100); p.spara(slump); System.out.println("Producenten producerar: " + slump); try { Thread.sleep(1000); } catch (InterruptedException ex) {} } } } //Innehåller funktioner för en konsument som skall "konsumera" (i detta fall avläsa det som producenten producerat) class Konsument implements Runnable { Produkt p; public Konsument(Produkt prod) { p = prod; } public void run() { while(true) { System.out.println("Konsumenten konsumerar: " + p.hamta()); } } }