Commit 3616ae49 authored by Gabriele Civitarese's avatar Gabriele Civitarese

initialized project

parent 0847d872
# java-concurrency-examples
Esempi di concorrenza e sincronizzazione in Java
\ No newline at end of file
import java.util.ArrayList;
import java.util.Random;
public class Main {
public static void main(String arg[]) throws Exception {
Random r = new Random();
ArrayList<Thread> threads = new ArrayList<Thread>();
//create some threads
for (int i=0; i<100; i++) {
MyThread mt = new MyThread(r);
threads.add(mt);
}
System.out.println("All threads have been created.");
//start all the threads
for (Thread t: threads) {
t.start();
}
System.out.println("All threads have been started.");
System.out.println("Start waiting for all thread to finish...");
//wait all the thread to finish
for (Thread t : threads) {
t.join();
}
System.out.println("...All thread finished!");
}
}
import java.util.Random;
public class MyThread extends Thread {
private Random rnd;
MyThread(Random r) {
rnd = r;
}
public void run() {
int seconds = rnd.nextInt(10) + 1;
System.out.println("A thread started!");
try
{
Thread.sleep(seconds * 1000);
}
catch(Exception ex)
{
ex.printStackTrace();
}
System.out.println("A thread died!");
}
}
public class Consumer implements Runnable {
private final Queue queue;
private final String id;
public Consumer(String id, Queue q) {
this.id = id;
queue = q;
}
public void run() {
while (true) {
consume(queue.take());
}
}
public void consume(String message) {
System.out.println("Cons. " + id + ": prelevato " + message);
}
}
public class Main {
public static void main(String[] args) {
Queue q = new Queue();
Producer p1 = new Producer("p1", q);
Producer p2 = new Producer("p2", q);
Producer p3 = new Producer("p3", q);
Consumer c1 = new Consumer("c1", q);
Consumer c2 = new Consumer("c2", q);
new Thread(p1).start();
new Thread(p2).start();
new Thread(p3).start();
new Thread(c1).start();
new Thread(c2).start();
}
}
\ No newline at end of file
public class Producer implements Runnable {
private final String id;
private final Queue queue;
public Producer(String id, Queue q) { this.id = id; queue = q; }
public void run() {
while (true) {
String message = produce();
System.out.println("Prod. " + id + ": inserisco " + message);
queue.put(message);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private int counter = 0;
public String produce() {
counter++;
return "Messaggio da " + id + " n. " + counter;
}
}
import java.util.ArrayList;
public class Queue {
public ArrayList<String> buffer = new ArrayList<String>();
public synchronized void put(String message) {
buffer.add(message);
notify();
}
public synchronized String take() {
String message = null;
while(buffer.size() == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(buffer.size()>0){
message = buffer.get(0);
buffer.remove(0);
}
return message;
}
}
public class Consumer implements Runnable {
private final Queue queue;
private final String id;
public Consumer(String id, Queue q) { this.id = id; queue = q; }
public void run() {
while (true) {
consume(queue.take());
}
}
public void consume(String message) {
System.out.println("Cons. " + id + ": prelevato " + message);
}
}
public class Main {
public static void main(String[] args) {
Queue q = new Queue();
Producer p = new Producer("p1", q);
Consumer c1 = new Consumer("c1", q);
Consumer c2 = new Consumer("c2", q);
new Thread(p).start();
new Thread(c1).start();
new Thread(c2).start();
}
}
\ No newline at end of file
public class Producer implements Runnable {
private final String id;
private final Queue queue;
public Producer(String id, Queue q) { this.id = id; queue = q; }
public void run() {
while (true) {
String message = produce();
System.out.println("Prod. " + id + ": inserisco " + message);
queue.put(message);
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}
private int counter = 0;
public String produce() {
counter++;
return "Messaggio n. " + counter;
}
}
import java.util.ArrayList;
//Esempio di coda condivisa che non usa wait e notify
//Quindi questo e' un esempio di come le cose NON vanno fatte (vedi busy waiting)
public class Queue {
public ArrayList<String> buffer = new ArrayList<String>();
public void put(String message) {
buffer.add(message);
}
public String take() {
String message = null;
if(buffer.size() > 0) {
message = buffer.get(0);
buffer.remove(0);
}
return message;
}
}
import java.util.ArrayList;
import java.util.Random;
//Utilizzo di un semaforo "fatto a "
public class Main {
public static void main(String arg[]) throws Exception {
Random r = new Random();
ArrayList<Thread> threads = new ArrayList<Thread>();
Semaphore s = new Semaphore(4);
//create some threads
for (int i=0; i<10; i++) {
MyThread mt = new MyThread(r, i, s);
threads.add(mt);
}
//start all the threads
for (Thread t: threads) {
t.start();
}
}
}
import java.util.Random;
public class MyThread extends Thread {
private Random rnd;
private int id;
private Semaphore sem;
MyThread(Random r, int i, Semaphore s) {
rnd = r;
id = i;
sem=s;
}
public void run() {
wasteSomeTime(); //Simulate the thread is doing something else
System.out.println("Thread " + id + " wants to enter in the critical region");
sem.enter();
System.out.println("Thread " + id + " entered in the critical region!");
wasteSomeTime(); //it takes some times to compleate the work in the critical region
System.out.println("Thread " + id + " is going to get out from the critical region");
sem.exit();
}//end run
private void wasteSomeTime() {
int seconds = rnd.nextInt(10) + 1;
try {Thread.sleep(seconds*1000);}
catch(Exception ex) {ex.printStackTrace();}
}
} //end class
//Classe che implementa tramite wait e notify un Semaforo.
//Se non vi ricordate cosa sia un semaforo, google is your best friend.
public class Semaphore extends Thread {
private int maxNumber; //numero massimo di thread
private int threadsIn; //conteggio dei thread nell'area critica
Semaphore(int max) {
maxNumber = max;
threadsIn = 0;
}
public synchronized void enter() {
System.out.println("" + threadsIn + " in the critical region...");
//quando abbiamo raggiunto il numero massimo di thread, chi vuole entrare aspetta
if (threadsIn >= maxNumber) {
try {this.wait();}
catch(InterruptedException ie) {ie.printStackTrace();}
}
threadsIn++;
}
public synchronized void exit() {
threadsIn--;
//quando un thread esce dall'area critica, sveglia qualcuno in attesa di entrare (se presente)
this.notify();
}
}
import java.util.Random;
import java.util.Vector;
import java.util.concurrent.Semaphore;
//Java ci offre utili strumenti per gestire la concorrenza (java.util.concurrent)
//Ecco un esempio, utilizzando l'implementazione dei semafori di questa libreria
//VIETATO USARE QUESTE LIBRERIE NEL PROGETTO
public class Main {
public static void main(String arg[]) throws Exception {
Random r = new Random();
Vector<Thread> threads = new Vector<Thread>();
Semaphore s = new Semaphore(2); //this is a standard class in Java
//create some threads
for (int i=0; i<10; i++) {
MyThread mt = new MyThread(r, i, s);
threads.add(mt);
}
//start all the threads
for (Thread t: threads) {
t.start();
}
}
}
import java.util.Random;
import java.util.concurrent.Semaphore;
public class MyThread extends Thread {
private Random rnd;
private int id;
private Semaphore sem;
MyThread(Random r, int i, Semaphore s) {
rnd = r;
id = i;
sem=s;
}
public void run() {
wasteSomeTime(); //Simulate the thread is doing something else
System.out.println("Thread " + id + " wants to enter in the critical region");
try{
sem.acquire();
}
catch(InterruptedException ie) {
ie.printStackTrace();
}
System.out.println("Thread " + id + " entered in the critical region!");
wasteSomeTime(); //it takes some times to complete the work in the critical region
System.out.println("Thread " + id + " is going to get out from the critical region");
sem.release();
}//end run
private void wasteSomeTime() {
int seconds = rnd.nextInt(10) + 1;
try {
Thread.sleep(seconds*1000);
}
catch(Exception ex) {
ex.printStackTrace();
}
}
} //end class
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment