Strumenti Utente

Strumenti Sito


lpr-b:lpr-b-09:soluzioni

Differenze

Queste sono le differenze tra la revisione selezionata e la versione attuale della pagina.

Link a questa pagina di confronto

Prossima revisione
Revisione precedente
lpr-b:lpr-b-09:soluzioni [22/10/2009 alle 19:50 (16 anni fa)] – creata Andrea Corradinilpr-b:lpr-b-09:soluzioni [22/10/2009 alle 20:42 (16 anni fa)] (versione attuale) Andrea Corradini
Linea 1: Linea 1:
-==== Task Thread: Es 1 ====+====== Alcune soluzioni proposte ====== 
 + 
 +[[esercizi|Torna alla pagina degli esercizi proposti]] 
 + 
 +[[FAQ|FAQ]] 
 + 
 + 
 +====== Tasks Threads ====== 
 + 
 +===== PrintTask =====
  
 <code:java> <code:java>
Linea 48: Linea 57:
  threadExecutor.shutdown();  threadExecutor.shutdown();
  }  }
 +}
 +</code>
 +
 +===== SleepTask =====
 +
 +<code:java>
 +public class SleepTask implements Runnable
 +{
 + private long start = 0;
 + private long end = 0;
 + private final long SLEEP_TIME = 10000;
 +
 + public void run()
 + {
 + try
 + {
 + start = System.currentTimeMillis();
 + Thread.sleep(SLEEP_TIME);
 + }catch(InterruptedException x)
 + {
 + end = System.currentTimeMillis();
 + System.out.println("TaskSleep - interrotto dopo " + (end - start) + " ms");
 + }
 + }
 +
 + public static void main(String[] args)
 + {
 + final long MAX_TIME = 5000;
 + SleepTask task = new SleepTask();
 + Thread t = new Thread(task);
 + System.out.println("main - avvio il thread");
 + t.start();
 +
 + try
 + {
 + Thread.sleep(MAX_TIME);
 + }catch(InterruptedException x){}
 +
 + System.out.println("main - eseguo la interrupt sul thread");
 + t.interrupt();
 + System.out.println("main - fine del main");
 + }
 +}
 +</code>
 +
 +===== PITask2 =====
 +
 +<code:java>
 +public class PITask2 implements Runnable
 +{
 + private double piEstimate = 0.0;
 + private long iteration = 0;
 + private int sign = -1;
 + private double accuracy;
 + private Thread main;
 +
 + public PITask2(double accuracy, Thread main)
 + {
 + this.accuracy = accuracy;
 + this.main = main;
 + }
 +
 + public void run()
 + {
 + System.out.println("Valore di Math.PI = " + Math.PI);
 + while(!Thread.currentThread().isInterrupted()
 + && Math.abs(piEstimate - Math.PI) > accuracy)
 + {
 + iteration++;
 + sign = -sign;
 + piEstimate += sign * 4.0 / ((2 * iteration) - 1);
 + }
 + if(Math.abs(piEstimate - Math.PI) > accuracy)
 + System.out.println("Thread interrotto");
 + else
 + main.interrupt();
 + System.out.println("Valore calcolato di PI = " + piEstimate);
 + }
 +
 + public static void main(String[] args)
 + {
 + double accuracy = 0.000000001;
 + long sleepTime = 5000;
 + if(args.length > 1)
 + {
 + accuracy = Math.pow(10, -1 * Integer.parseInt(args[0]));
 + sleepTime = Integer.parseInt(args[1]) * 1000;
 + }
 + System.out.println("Accuracy = " + accuracy);
 + PITask2 task = new PITask2(accuracy, Thread.currentThread());
 + Thread t = new Thread(task);
 + t.start();
 + try
 + {
 + t.join(sleepTime);
 + if(t.isAlive()) t.interrupt();
 + }catch(InterruptedException x)
 + {
 + System.out.println("Main interrotto");
 + }
 + System.out.println("Fine main");
 + }
 +}
 +</code>
 +
 +====== Thread Pool ======
 +
 +===== AsynchronousCalculator =====
 +
 +<code:java>
 +import java.io.BufferedReader;
 +import java.io.IOException;
 +import java.io.InputStreamReader;
 +import java.util.concurrent.*;
 +
 +public class AsynchronousCalculator
 +{
 + public static void main(String[] args)
 + {
 + ExecutorService exec = Executors.newCachedThreadPool();
 + boolean quit = false;
 + while(!quit)
 + {
 + System.out.println("Inserisci l'espressione:");
 + BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 + String s = null;
 + try
 + {
 + s = br.readLine();
 + }catch(IOException e)
 + {
 + e.printStackTrace();
 + return;
 + }
 + if(s.startsWith("PI:"))
 + {
 + int value;
 + try
 + {
 + value = Integer.parseInt(s.substring(s.indexOf(':') + 1, s.length()));
 + }catch(Exception e)
 + {
 + System.out.println("Espressione non valida");
 + continue;
 + }
 + exec.execute(new PITask(value));
 + }
 + else if(s.startsWith("FIB:"))
 + {
 + int value;
 + try
 + {
 + value = Integer.parseInt(s.substring(s.indexOf(':') + 1, s.length()));
 + }catch(Exception e)
 + {
 + System.out.println("Espressione non valida");
 + continue;
 + }
 + exec.execute(new FibTask(value));
 + }
 + else if(s.startsWith("FACT:"))
 + {
 + int value;
 + try
 + {
 + value = Integer.parseInt(s.substring(s.indexOf(':') + 1, s.length()));
 + }catch(Exception e)
 + {
 + System.out.println("Espressione non valida");
 + continue;
 + }
 + exec.execute(new FactTask(value));
 + }
 + else if(s.equalsIgnoreCase("QUIT"))
 + {
 + quit = true;
 + }
 + else
 + {
 + System.out.println("Espressione non valida");
 + }
 + }
 + exec.shutdown();
 + System.out.println("Main esce");
 + }
 +}
 +</code>
 +
 +
 +===== Task =====
 +
 +<code:java>
 +import java.text.SimpleDateFormat;
 +import java.util.Date;
 +
 +public abstract class Task implements Runnable
 +{
 + public long creationTime;
 + public long startTime;
 + public long endTime;
 + public String result;
 +
 + public Task()
 + {
 + this.creationTime = System.currentTimeMillis();
 + }
 +
 + public abstract void compute();
 +
 + public void setResult(String result)
 + {
 + this.result = result;
 + }
 +
 + public void run()
 + {
 + this.startTime = System.currentTimeMillis();
 + compute();
 + this.endTime = System.currentTimeMillis();
 + printResult();
 + }
 +
 + public void printResult()
 + {
 + SimpleDateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss:SS");
 + String creationString = formatter.format(new Date(this.creationTime));
 + String startString = formatter.format(new Date(this.startTime));
 + String endString = formatter.format(new Date(this.endTime));
 +
 + System.out.println(Thread.currentThread().getName()
 + + ", creationTime = " + creationString + ", startTime = "
 + + startString + ", endTime = " + endString + ", " + result);
 + }
 +}
 +</code>
 +
 +===== PITask =====
 +
 +<code:java>
 +public class PITask extends Task
 +{
 + private double piEstimate = 0.0;
 + private long iteration = 0;
 + private int sign = -1;
 + private double accuracy;
 +
 + public PITask(int precision)
 + {
 + this.accuracy = Math.pow(10, -1 * precision);
 + }
 +
 + public void compute()
 + {
 + while(Math.abs(piEstimate - Math.PI) > accuracy)
 + {
 + iteration++;
 + sign = -sign;
 + piEstimate += sign * 4.0 / ((2 * iteration) - 1);
 + }
 + setResult("Pigreco = " + piEstimate + ", accuracy = " + this.accuracy);
 + }
 +}
 +</code>
 +
 +===== FibTask =====
 +
 +<code:java>
 +public class FibTask extends Task
 +{
 + int value;
 +
 + public FibTask(int value)
 + {
 + this.value = value;
 + }
 +
 + private int fib(int n)
 + {
 + if(n == 0 || n == 1) return n;
 + if(n == 1) return 1;
 + return fib(n - 1) + fib(n - 2);
 + }
 +
 + public void compute()
 + {
 + int result = this.fib(value);
 + setResult("Fib(" + value + ") = " + result);
 + }
 +}
 +</code>
 +
 +
 +===== FactTask =====
 +
 +<code:java>
 +public class FactTask extends Task
 +{
 + int value;
 +
 + public FactTask(int value)
 + {
 + this.value = value;
 + }
 +
 + private long fact(int n)
 + {
 + if(n == 0) return 1;
 + if(n == 1) return 1;
 + return(n * fact(n - 1));
 + }
 +
 + public void compute()
 + {
 + long result = this.fact(value);
 + setResult("Fact(" + value + ") = " + result);
 + }
 +}
 +</code>
 +
 +====== Indirizzi IP ======
 +
 +===== ListInterface =====
 +<code:java>
 +import java.util.Enumeration;
 +import java.net.*;
 +
 +public class ListInterface
 +{
 +    public static void main(String[] args)
 +    {
 + try
 +     {
 + Enumeration<NetworkInterface> interfaceList = NetworkInterface.getNetworkInterfaces();
 + if(interfaceList == null)
 +     {
 + System.out.println("Nessuna interfaccia di rete disponibile");
 +     }
 + else
 +     {
 + while(interfaceList.hasMoreElements())
 +     {
 + NetworkInterface iface = interfaceList.nextElement();
 + System.out.println("Interface " + iface.getName() + ":->" + iface.getDisplayName());
 + Enumeration<InetAddress> addrList = iface.getInetAddresses();
 + while(addrList.hasMoreElements())
 +     {
 + InetAddress address = addrList.nextElement();
 + System.out.print("\tIndirizzo " + ((address instanceof Inet4Address ? "(v4)"
 +     : (address instanceof Inet6Address ? "(v6)" : "(?)"))));
 + System.out.println(": " + address.getHostAddress());
 +     }
 +     }
 +     }
 +     }catch(SocketException e) { System.out.println(e);}
 +    }
 } }
 </code> </code>
lpr-b/lpr-b-09/soluzioni.1256241011.txt.gz · Ultima modifica: 22/10/2009 alle 19:50 (16 anni fa) da Andrea Corradini

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki