Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return f.isDirectory(); rekVypis(System.getProperty("user.dir")); } } public class PodadresareRek { static void rekVypis(String aktualnyAdr) { String[] mena; File aktDir = new File(aktualnyAdr); FilterAdresara FilterAdr = new FilterAdresara(); mena = aktDir.list(FilterAdr); if (mena != null) { for (int i = 0; i < mena.length; i++) { String podadr = new String (aktualnyAdr + "\\" + mena[i]); System.out.println(podadr); rekVypis(podadr); } } Serializácia ObjectOutputStream FileOutputStream out = new FileOutputStream("AVL"); ObjectOutputStream fs = new ObjectOutputStream(out); fs.writeObject("avl"); // String AVL: fs.writeObject(s); // AVLTree ¬í t avlsr AVLTree¡6ûG‰> L roott LAVLNode;xpsr AVLNodeÙ=œö½âI fs.flush(); xL leftq ~ L rightq ~ xp ssq ~ /sq ~ sq ~ ppsq ~ ppsq ~ Qsq ~ @ppsq ~ ~ •sq ~ „ppsq ~ ¦psq ~ ·pp ObjectInputStream FileInputStream in = new FileInputStream("AVL"); ObjectInputStream is = new ObjectInputStream(in); String str = (String)is.readObject(); AVLTree ss = (AVLTree)is.readObject(); Serializable Interface class AVLNode implements Serializable class AVLTree implements Serializable bppsq Typ enum enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }; … Days.SUNDAY … enum public enum Planet { MERCURY (3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), EARTH (5.976e+24, 6.37814e6), MARS (6.421e+23, 3.3972e6); private final double mass; //[kg] private final double radius; //[m] Planet(double mass, double radius) { this.mass = mass; this.radius = radius; } //gravitational constant [m3 kg-1 s-2] public static final double G = 6.673E-11; public double surfaceGravity() { return G * mass / (radius * radius); } } enum public static void main(String[] args) { double earthWeight = Double.parseDouble(args[0]); double mass = earthWeight/EARTH.surfaceGravity(); for (Planet p : Planet.values()) { System.out.printf("Your weight on %s is %f%n", p, p.surfaceGravity()*mass); } } $ java Planet 175 Your weight on MERCURY is 66.107583 Your weight on VENUS is 158.374842 Your weight on EARTH is 175.000000 Your weight on MARS is 66.279007 Generics public interface List <E> { void add(E x); Iterator<E> iterator(); } public interface Iterator<E> { E next(); boolean hasNext(); } List<Integer> List<List<Integer>> public interface ListList { void add(List<Integer> x); Iterator<List<Integer>> iterator(); List<String> } public interface StringList { void add(String x); Iterator<String> iterator(); } public interface IntegerList { void add(Integer x); Iterator<Integer> iterator(); } Generics Ak String je podtyp Object, aký je vzťah List(String) a List(Object) ? List<String> ls = new ArrayList<String>(); List<Object> lo = ls; lo.add(new Object()); String s = ls.get(0); List(String) nie je podtyp List(Object) !!! Generics public class superclass { public void Too() { } } public class subclass extends superclass { public void too() { } } public static void foo(superclass x) { } public static void goo(subclass x) { } public static superclass Hoo() { return new superclass(); } public static subclass hoo() { return new subclass(); } foo(new subclass()); goo(new superclass()); superclass supcl = hoo(); subclass subcl = Hoo(); hoo().too(); hoo().Too(); Hoo().too(); Hoo().Too(); Generics void printCollection(Collection c) { Iterator i = c.iterator(); for (k = 0; k < c.size(); k++) System.out.println(i.next()); } void printCollection(Collection<Object> c) { for (Object e : c) System.out.println(e); } Collection<Object> nie je supertype Collections void printCollection(Collection<?> c) { for (Object e : c) System.out.println(e); } Generics public abstract class Shape; public class Circle extends Shape; public class Rectangle extends Shape; public void addRectangle(List<? extends Shape> shapes) { shapes.add(0, new Rectangle()); // Compile-time error! } Reflection model Class c = subclass.class; Class c1 = Class.forName("subclass"); Class c2 = java.awt.Button.class; Class s = c.getSuperclass(); System.out.println(s.getName()); int m = c.getModifiers(); if (Modifier.isPublic(m)) System.out.println("public"); Class[] theInterfaces = c.getInterfaces(); for (int i = 0; i < theInterfaces.length; i++) { String interfaceName = theInterfaces[i].getName(); System.out.println(interfaceName); Premenné, konštruktory Field[] publicFields = c.getFields(); for (int i = 0; i < publicFields.length; i++) { String fieldName = publicFields[i].getName(); Class typeClass = publicFields[i].getType(); String fieldType = typeClass.getName(); System.out.println("Name: " + fieldName + ", Type: " + fieldType); } Constructor[] theConstructors = c.getConstructors(); for (int i = 0; i < theConstructors.length; i++) { System.out.print("( "); Class[] parameterTypes = theConstructors[i].getParameterTypes(); for (int k = 0; k < parameterTypes.length; k ++) { String parameterString = parameterTypes[k].getName(); System.out.print(parameterString + " "); } System.out.println(")"); } Reflection – metódy Method[] theMethods = c.getMethods(); for (int i = 0; i < theMethods.length; i++) { String methodString = theMethods[i].getName(); System.out.println("Name: " + methodString); String returnString = theMethods[i].getReturnType().getName(); System.out.println(" Return Type: " + returnString); Class[] parameterTypes = theMethods[i].getParameterTypes(); System.out.print(" Parameter Types:"); for (int k = 0; k < parameterTypes.length; k ++) { String parameterString = parameterTypes[k].getName(); System.out.print(" " + parameterString); } System.out.println(); } Volanie konštruktora Class classDefinition = Class.forName(className); Object object = classDefinition.newInstance(); Class rectangleDefinition = Class.forName("java.awt.Rectangle"); Class[] intArgsClass = new Class[] {int.class, int.class}; Constructor intArgsConstructor = rectangleDefinition.getConstructor(intArgsClass); Object[] intArgs = new Object[] {new Integer(12), new Integer(34)}; Rectangle rectangle = (Rectangle) createObject(intArgsConstructor, intArgs); Volanie metódy public static String append(String firstWord, String secondWord) { String result = null; try { Class[] parameterTypes = new Class[] {String.class}; Class c = String.class; Method concatMethod = c.getMethod("concat", parameterTypes); Object[] arguments = new Object[] {secondWord}; result = (String) concatMethod.invoke(firstWord, arguments); } catch (Exception e) { .... } return result; } Dnes bude • • • • • • concurrency vs. parallelism threads alias processes synchronizácia kritická sekcia deadlock komunikácia (cez pipes) Inšpirácia • http://www.doc.ic.ac.uk/~jnm/book/book_applets/concurrency.html package java.lang.Thread • • new Thread() alebo jeho subclass metóda run() Vytvorenie threadu public class SimpleThread extends Thread { private int countDown = 5; private static int threadCount = 0; public SimpleThread() { super("" + (++threadCount)); start(); } public String toString() { return "#" + getName() + ": " + countDown; } public void run() { while(true) { System.out.println(this); if(--countDown == 0) return; } } public static void main(String[] args) { for(int i = 0; i < 5; i++) new SimpleThread(); } } #1: 5 #1: 4 #1: 3 #1: 2 #1: 1 #2: 5 #2: 4 #2: 3 #2: 2 #2: 1 #3: 5 #3: 4 #3: 3 #3: 2 #3: 1 #4: 5 #4: 4 #4: 3 #4: 2 #4: 1 #5: 5 #5: 4 #5: 3 #5: 2 #5: 1 #1: 5 #2: 5 #3: 5 #4: 5 #5: 5 #5: 4 #4: 4 #5: 3 #5: 2 #3: 4 #5: 1 #2: 4 #4: 3 #1: 4 #3: 3 #4: 2 #2: 3 #4: 1 #3: 2 #1: 3 #2: 2 #3: 1 #1: 2 #2: 1 #1: 1 public void run() { while(true) { System.out.println(this); for(int j=0; j<(5-ind)*10000000 double gg = 0-Math.PI+j+j-j if(--countDown == 0) return; } } • yield() – daj šancu iným Uvoľnenie threadu public class YieldingThread extends Thread { private int countDown = 5; private static int threadCount = 0; #1: 5 #2: 5 public YieldingThread() { #3: 5 super("" + ++threadCount); #4: 5 #5: 5 start(); #1: 4 } #2: 4 #3: 4 public String toString() {... } #4: 4 public void run() { #5: 4 #1: 3 while(true) { #2: 3 System.out.println(this); #3: 3 #4: 3 if(--countDown == 0) return; #5: 3 yield(); #1: 2 #2: 2 } #3: 2 } #4: 2 #5: 2 public static void main(String[] args) { #1: 1 for(int i = 0; i < 5; i++) #2: 1 #3: 1 new YieldingThread(); #4: 1 } #5: 1 } MAX_PRIORITY MIN_PRIORITY NORM_PRIORITY setPriority(int newPriority) interval [1..10] Priority threadu public class SimplePriorities extends Thread { private int countDown = 5; private volatile double d = 0; // No optimization public SimplePriorities(int priority) { setPriority(priority); start(); } public void run() { while(true) { for(int i = 1; i < 100000; i++) d = d + (Math.PI + Math.E) / (double)i; System.out.println(this); if(--countDown == 0) return; } } public static void main(String[] args) { new SimplePriorities(Thread.MAX_PRIORITY); for(int i = 0; i < 5; i++) new SimplePriorities(Thread.MIN_PRIORITY); } } [Thread-0,10,main]: 5 [Thread-0,10,main]: 4 [Thread-0,10,main]: 3 [Thread-0,10,main]: 2 [Thread-0,10,main]: 1 [Thread-1,1,main]: 5 [Thread-1,1,main]: 4 [Thread-1,1,main]: 3 [Thread-1,1,main]: 2 [Thread-1,1,main]: 1 [Thread-2,1,main]: 5 [Thread-2,1,main]: 4 [Thread-2,1,main]: 3 [Thread-2,1,main]: 2 [Thread-2,1,main]: 1 [Thread-3,1,main]: 5 [Thread-3,1,main]: 4 [Thread-3,1,main]: 3 [Thread-3,1,main]: 2 [Thread-3,1,main]: 1 [Thread-4,1,main]: 5 [Thread-4,1,main]: 4 [Thread-4,1,main]: 3 [Thread-4,1,main]: 2 [Thread-4,1,main]: 1 [Thread-5,1,main]: 5 [Thread-5,1,main]: 4 [Thread-5,1,main]: 3 [Thread-5,1,main]: 2 [Thread-5,1,main]: 1 [Thread-1,10,main]: 5 [Thread-1,10,main]: 4 [Thread-1,10,main]: 3 [Thread-1,10,main]: 2 [Thread-1,10,main]: 1 [Thread-3,8,main]: 5 [Thread-3,8,main]: 4 [Thread-3,8,main]: 3 [Thread-3,8,main]: 2 [Thread-3,8,main]: 1 [Thread-4,7,main]: 5 [Thread-4,7,main]: 4 [Thread-4,7,main]: 3 [Thread-4,7,main]: 2 [Thread-4,7,main]: 1 [Thread-0,1,main]: 5 [Thread-0,1,main]: 4 [Thread-0,1,main]: 3 [Thread-0,1,main]: 2 [Thread-0,1,main]: 1 [Thread-2,1,main]: 5 [Thread-2,1,main]: 4 [Thread-2,1,main]: 3 [Thread-2,1,main]: 2 [Thread-2,1,main]: 1 [Thread-5,2,main]: 5 [Thread-5,2,main]: 4 [Thread-5,2,main]: 3 [Thread-5,2,main]: 2 [Thread-5,2,main]: 1 sleep(long millis) throws InterruptedException join() čakaj kým umre Uspatie threadu public class SleepingThread extends Thread { private int countDown = 5; private static int threadCount = 0; public SleepingThread() { … } public void run() { while(true) { System.out.println(this); if(--countDown == 0) return; try { sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } } } public static void main(String[] args) throws InterruptedException { for(int i = 0; i < 5; i++) new SleepingThread().join(); System.out.println("--"); } } #1: 5 #1: 4 #1: 3 #1: 2 #1: 1 -#2: 5 #2: 4 #2: 3 #2: 2 #2: 1 -#3: 5 #3: 4 #3: 3 #3: 2 #3: 1 -#4: 5 #4: 4 #4: 3 #4: 2 #4: 1 -#5: 5 #5: 4 #5: 3 #5: 2 #5: 1 -- Čakanie na thread class Sleeper extends Thread { private int duration; public Sleeper(String name, int sleepTime) { super(name); duration = sleepTime; start(); } public void run() { try { sleep(duration); } catch (InterruptedException e) { System.out.println(getName() + " was interrupted. " + "isInterrupted(): " + isInterrupted()); return; } System.out.println(getName() + " has awakened"); } } Sleeper prvy = new Sleeper("Prvy", 1500); Sleeper druhy = new Sleeper("Druhy", 1500), Joiner treti = new Joiner("Treti", druhy), Joiner stvrty = new Joiner("Strvrty", prvy); prvy.interrupt(); class Joiner extends Thread { private Sleeper sleeper; public Joiner(String name, Sleeper sleeper) { super(name); this.sleeper = sleeper; start(); } public void run() { try { sleeper.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println(getName() + " completed"); } } Prvy was interrupted. isInterrupted(): false Strvrty completed Druhy has awakened Treti completed Rúry class Sender extends Thread { class Receiver extends Thread { private Random rand = new Random(); private PipedReader in; private PipedWriter out = new PipedWriter(); public Receiver(Sender sender) throws IOException { public PipedWriter getPipedWriter() { return out; } in = new PipedReader(sender.getPipedWriter()); public void run() { } while(true) { public void run() { for(char c = 'A'; c <= 'z'; c++) { try { try { while(true) { out.write(c); System.out.println("Read: " + (char)in.read()); sleep(rand.nextInt(500)); } } catch(Exception e) { } catch(IOException e) { Read: A throw new RuntimeException(e); throw new RuntimeException(e); Read: B Read: C } } Read: D } } Read: E } } Read: F } Read: G } Read: H Read: I public class PipedIO { Read: J public static void main(String[] args) throws Exception { Read: K Sender sender = new Sender(); Read: L Receiver receiver = new Receiver(sender); Read: M sender.start(); Read: N receiver.start(); Read: O Terminated new Timeout(4000, "Terminated"); Read: P } Read: Q } Read: R public class Gulicka extends Thread { public int x = ..., y = …, dx = …, dy = … public void run() { while (true) { x += dx; y += dy; if (x >= sizeX) { x = sizeX - (x-sizeX); dx = -dx; } else if (y >= sizeY) { y = sizeY - (y-sizeY); dy = -dy; } else if (x < 0) { x = -x; dx = -dx; } else if (y < 0) { y = -y; dy = -dy; } ap.repaint(); try { sleep(10); } catch(Exception e) {} } } } Guličky - thready public class Ball extends Applet { Gulicka th1, th2; ..... public void start() { th1 = new Gulicka (this); th1.setPriority(Thread.MAX_PRIORITY); th1.start(); th2 = new Gulicka (this); th2.setPriority(Thread.MIN_PRIORITY); th2.start(); } public void update(Graphics g) { showStatus(th1.steps + " " + th2.steps); g.drawImage(img,0,0,this); g.setColor(Color.BLUE); g.drawRect(th1.x,th1.y,2,2); g.setColor(Color.RED); g.drawRect(th2.x,th2.y,2,2); } .... } Guličky - applet Sorty public class Sapplet extends Applet { SortPanel c1, c2, c3, c4; public void init() { setSize(800,200); setLayout(new GridLayout(1,4)); c1 = new SortPanel("Buble",Color.MAGENTA); add(c1); c2 = new SortPanel("Quick",Color.BLUE); add(c2); c3 = new SortPanel("Merge",Color.RED); add(c3); c4 = new SortPanel("Random",Color.GREEN); add(c4); } public void start() { c1.start(); c2.start(); c3.start(); c4.start(); } } SortPanel, Canvas public class SortPanel extends Panel { SortThread thread ; GraphicCanvas can; int[] a; .... public void start() { a = new int[100]; for(int i=0; i < a.length; i++) a[i] = (int)(200*Math.random()); thread = new SortThread(can, algo, a); thread.start(); } } public class GraphicCanvas extends Canvas { .... public void swap(int i, int j) { lo = i; hi = j; } public void update(Graphics g) { g.clearRect(0,0,200,200); Color cl = g.getColor(); for(int i=0; i < sp.a.length; i++) { g.setColor((i == lo || i == hi)? Color.BLACK:cl); g.drawLine(2*i,sp.a[i],2*i,0); //g.drawLine(2*i,sp.a[i],2*i,sp.a[i]); } } } public class SortThread extends Thread { GraphicCanvas can; public void run() { if (algo.equals("Buble")) bubleSort(a); .... else randomSort(a); } void swap(int i, int j) { can.swap(i,j); can.repaint(); try{ sleep(10); } catch(Exception e) {} } void randomSort(int a[]) { while(true) { int i = (int)((a.length-1)*Math.random()); int j = (int)((a.length-1)*Math.random()); swap(i,j); if (i<j && a[i] > a[j]) { int pom = a[i]; a[i] = a[j]; a[j] = pom; } } } RandomSrt Semafóry public class Semaphore implements Invariant { private volatile int semaphore = 0; public boolean available() { return semaphore == 0; } public void acquire() { ++semaphore; } public void release() { --semaphore; } public InvariantState invariant() { int val = semaphore; return(val == 0 || val == 1)? new InvariantOK(): new InvariantFailure(new Integer(val)); } public class SemaphoreTester extends Thread { .... public void run() { while(true) if(semaphore.available()) { yield(); // skor to rachne semaphore.acquire(); yield(); semaphore.release(); yield(); } } public static void main(String[] args) throws Exception { Semaphore sem = new Semaphore(); } new SemaphoreTester(sem); new SemaphoreTester(sem); new InvariantWatcher(sem).join(); java SemaphoreTester Invariant violated: 2 } } Synchronizácia public class SynchronizedSemaphore extends Semaphore { private volatile int semaphore = 0; public synchronized boolean available() { return semaphore == 0; } public synchronized void acquire() { ++semaphore; } public synchronized void release() { --semaphore; } } ... a teraz to už pojde ? public void run() { while(true) if(semaphore.available()) { semaphore.acquire(); semaphore.release(); } } - atomická operácia vs. kritická sekcia Kritická sekcia Synchronizácia celej metódy public synchronized void doTask() { p.incrementX(); p.incrementY(); store(); } Kritická sekcia public void doTask() { synchronized(this) { p.incrementX(); p.incrementY(); } store(); } Stavy threadu • • • • new – nenaštartovaný ešte runnable – može bežať, keď mu bude pridelený CPU dead – keď skončí metóda run(), resp. po stop() blocked – niečo mu bráni, aby bežal – – – – sleep(miliseconds) – počká daný čas, ak nie je interrupted... wait(), resp. wait (miliseconds) čaká na správu notify() resp. notifyAll() , čaká na I/O, pokúša sa zavolať synchronized na metódu. resp. objekt ktorý je už v tom... sleep vs. wait keď proces volá wait(), výpočet je pozastavený, ale iné synchronizované metódy môžu byt volané Semafóry znova public class Semaphore { private int value; public Semaphore(int val) { value = val; } public synchronized void acquire() { while (value == 0) try { wait(); } catch (InterruptedException ie) { } value--; } public synchronized void release() { ++value; notify(); } java.util.concurrent.Semaphor } Večerajúci filozofovia class Fork { private boolean taken=false; private PhilCanvas display; private int identity; Fork(PhilCanvas disp, int id) { display = disp; identity = id;} synchronized void put() { taken=false; display.setFork(identity,taken); notify(); } synchronized void get() throws java.lang.InterruptedException { while (taken) wait(); taken=true; display.setFork(identity,taken); } } Večerajúci filozofovia 3 2 2 1 3 class Philosopher extends Thread { 4 4 ... public void run() { 0 try { while (true) { // thinking view.setPhil(identity,view.THINKING); sleep(controller.sleepTime()); // hungry view.setPhil(identity,view.HUNGRY); right.get(); // gotright chopstick view.setPhil(identity,view.GOTRIGHT); sleep(500); left.get(); // eating view.setPhil(identity,view.EATING); sleep(controller.eatTime()); right.put(); left.put(); } } catch (java.lang.InterruptedException e){} } } 0 1 Večerajúci filozofovia for (int i =0; i<N; ++i) fork[i] = new Fork(display,i); for (int i =0; i<N; ++i){ phil[i] = new Philosopher (this,i,fork[(i-1+N)%N],fork[i]); phil[i].start(); } Phil 0 thinking Phil 0 has Chopstick 0 Waiting for Chopstick 1 Phil 0 eating Phil 0 thinking Phil 0 has Chopstick 0 Waiting for Chopstick 1 Phil 0 eating Phil 0 thinking Phil 0 has Chopstick 0 Waiting for Chopstick 1 Phil 0 eating Phil 0 thinking Phil 0 has Chopstick 0 Waiting for Chopstick 1 Phil 0 eating Phil 0 thinking Phil 0 has Chopstick 0 Waiting for Chopstick 1 Phil 0 eating Phil 0 thinking Phil 0 has Chopstick 0 Waiting for Chopstick 1 Phil 1 thinking Phil 2 thinking Phil 3 thinking Phil 4 thinking Phil 1 has Chopstick 1 Waiting for Chopstick 2 Phil 2 has Chopstick 2 Waiting for Chopstick 3 Phil 3 has Chopstick 3 Waiting for Chopstick 4 Phil 4 has Chopstick 4 Waiting for Chopstick 0 Ohraničený buffer public synchronized void put(Object o) throws InterruptedException { while (count==size) wait(); buf[in] = o; ++count; in=(in+1) % size; notify(); } public synchronized Object get() throws InterruptedException { while (count==0) wait(); Object o =buf[out]; buf[out]=null; --count; out=(out+1) % size; notify(); return (o); } Budík import java.util.Timer; import java.util.TimerTask; •schedule(TimerTask task, long delay, long period) •schedule(TimerTask task, Date time, long period) •scheduleAtFixedRate(TimerTask task, long delay, long period) •scheduleAtFixedRate(TimerTask task, Date firstTime, long period) public class Reminder { Timer timer; public Reminder(int seconds) { timer = new Timer(); timer.schedule(new RemindTask(), seconds*1000); } class RemindTask extends TimerTask { public void run() { System.out.println("Time's up!"); timer.cancel(); //Terminate the thread } //Get the Date corresponding to 11:01:00 pm today. } Calendar calendar = Calendar.getInstance(); public static void main(String args[]) { calendar.set(Calendar.HOUR_OF_DAY, 23); new Reminder(5); calendar.set(Calendar.MINUTE, 1); System.out.println("Task scheduled."); calendar.set(Calendar.SECOND, 0); } Date time = calendar.getTime(); } timer = new Timer(); timer.schedule(new RemindTask(), time);