You are on page 1of 3

/*MIHAILA MALINA-CRISTIANA TST an III gr.

2331

8. ?apte copii mpart o pung de bomboane. Fiecare se serve?te cu cte o bomboan. Punga con?ine o singur bomboan amar (numr ntreg citit de la tastatur). Cel care o gse?te ia restul pungii pentru sine. Realiza?i o aplica?ie care cite?te un numr de la tastatur, reprezentnd numrul de bom boane din pung. Se cite?te apoi un al doilea numr, mai mic dect primul, care reprezint numrul bomboa nei amare. Instan?ia?i 7 threaduri care au acces la bomboane ?i extrag numere aleatoare din ea. Threadul care nimere?te bomboana amar va termina aplica?ia prin afi?area unu i mesaj.

import java.io.DataInputStream; import java.io.IOException;

class Buffer { private int number = -1; int m; public Buffer(int a) { m=a; } private boolean available = false; public synchronized int get() { while (!available) { try { wait(); } catch (InterruptedException e) { } } number=(int)Math.random()*m; available = false; notifyAll(); return number; } } class Kids extends Thread{ public Kids(ThreadGroup group, String threadName) { super(group, threadName); } private Buffer buffer; int bitter;

public Kids(Buffer b, int p, ThreadGroup group) { buffer = b; bitter=p; } public void run() { int value = buffer.get(); while(value!=bitter){ value=buffer.get(); System.out.println(" a primit bomboana "+value); notifyAll(); } System.out.println(this.getName()+" a luat bomboana amara si pla nge"); } } public class Candys { public static void main(String[] args) { String s=null; int m,p; System.out.println("Insert the no. of candys: "); DataInputStream in=new DataInputStream(System.in); try { s=in.readLine(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Which is the bitter candy?"); m=Integer.parseInt(s); try { s=in.readLine(); } catch (IOException e) { e.printStackTrace(); }

p=Integer.parseInt(s); try { s=in.readLine(); } catch (IOException e) {

e.printStackTrace(); } Buffer b=new Buffer(m); ThreadGroup group=new ThreadGroup("Group 1"); Kids k1=new Kids(b,p,group); Kids k2=new Kids(b,p,group); Kids k3=new Kids(b,p,group); Kids k4=new Kids(b,p,group); Kids k5=new Kids(b,p,group); Kids k6=new Kids(b,p,group); Kids k7=new Kids(b,p,group); k1.setPriority(10); k1.start(); k2.start(); k3.start(); k4.start(); k5.start(); k6.start(); k7.start(); group.list(); Thread[] threads = new Thread[group.activeCount()]; group.enumerate(threads); } }

You might also like