Commit 956ddbc7 authored by Luca Arrotta's avatar Luca Arrotta

first commit

parent c3502d55
setup_SDP
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="CompilerConfiguration"> <component name="CompilerConfiguration">
<bytecodeTargetLevel target="1.8" /> <bytecodeTargetLevel target="11" />
</component> </component>
</project> </project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings"> <component name="GradleSettings">
<option name="linkedExternalProjectsSettings"> <option name="linkedExternalProjectsSettings">
<GradleProjectSettings> <GradleProjectSettings>
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
<component name="FrameworkDetectionExcludesConfiguration"> <component name="FrameworkDetectionExcludesConfiguration">
<file type="web" url="file://$PROJECT_DIR$" /> <file type="web" url="file://$PROJECT_DIR$" />
</component> </component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK"> <component name="ProjectRootManager" version="2" languageLevel="JDK_11" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" /> <output url="file://$PROJECT_DIR$/out" />
</component> </component>
</project> </project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
\ No newline at end of file
# Setup test SDP # Lab2 Examples
This repository contains a simple example that enables you to test if the **IntelliJ** IDE works correctly.
* You can import the project directly from a **V**ersion **C**ontrol **S**ystem, by providing the following URL: * Threads Join
https://ewserver.di.unimi.it/gitlab/riccardopresotto/setup_test_sdp.git
<img src = './assets/img_1.png'> * Wait & Notify
* Otherwise, take care to import the project as a Gradle Project * Producer-Consumer
* The testing files are located in the directory: *setup\_test\_sdp/src/main/java*
TCPServer.java join/Main.java
TCPServer join.Main
TCPClient.java join/MyThread.java
TCPClient join.MyThread
semaphore/Main.java
semaphore.Main
semaphore/MyThread.java
semaphore.MyThread
semaphore/Semaphore.java
semaphore.Semaphore
producerConsumer/Consumer.java
producerConsumer.Consumer
producerConsumer/Main.java
producerConsumer.Main
producerConsumer/Queue.java
producerConsumer.Queue
producerConsumer/Producer.java
producerConsumer.Producer
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception {
String sentence;
String modifiedSentence;
/* Inizializza l'input stream (da tastiera) */
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
/* Inizializza una socket client, connessa al server */
Socket clientSocket = new Socket("localhost", 6789);
/* Inizializza lo stream di output verso la socket */
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
/* Inizializza lo stream di input dalla socket */
BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
/* Legge una linea da tastiera */
sentence = inFromUser.readLine();
/* Invia la linea al server */
outToServer.writeBytes(sentence + '\n');
/* Legge la risposta inviata dal server (linea terminata da \n) */
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
/* Crea una "listening socket" sulla porta specificata */
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true) {
/*
* Viene chiamata accept (bloccante).
* All'arrivo di una nuova connessione crea una nuova
* "established socket"
*/
Socket connectionSocket = welcomeSocket.accept();
/* Inizializza lo stream di input dalla socket */
BufferedReader inFromClient =
new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
/* Inizializza lo stream di output verso la socket */
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
/* Legge una linea (terminata da \n) dal client */
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + '\n';
/* Invia la risposta al client */
outToClient.writeBytes(capitalizedSentence);
connectionSocket.close();
}
}
}
package join;
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<10; 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!");
}
}
package join;
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!");
}
}
package producerConsumer;
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);
}
}
package producerConsumer;
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();
}
}
package producerConsumer;
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;
}
}
package producerConsumer;
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;
}
}
package semaphore;
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>();
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();
}
}
}
package semaphore;
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
package semaphore;//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 {
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
while (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();
}
}
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