adresáre rekurzívne class filteradresara implements filenamefilter { public boolean accept(file...

38
Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return f.isDirectory(); } } 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); } } rekVypis(System.getProperty("user.dir"));

Upload: primrose-conley

Post on 13-Dec-2015

220 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return f.isDirectory(); }}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); } }

rekVypis(System.getProperty("user.dir"));

Page 2: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

SerializáciaObjectOutputStream

FileOutputStream out = new FileOutputStream("AVL");

ObjectOutputStream fs = new ObjectOutputStream(out);

fs.writeObject("avl"); // String

fs.writeObject(s); // AVLTree

fs.flush();

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 Serializableclass AVLTree implements Serializable

AVL:¬í t avlsr AVLTree¡6ûG‰> L roott LAVLNode;xpsr AVLNodeÙ=œö½â I xL leftq ~ L rightq ~ xp ssq ~ /sq ~ sq ~ ppsq ~ ppsq ~ Qsq ~ @ppsq ~ bppsq ~ •sq ~ „ppsq ~ ¦psq ~ ·pp

Page 3: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

Typ enum

enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };

… Days.SUNDAY …

Page 4: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

enumpublic 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); }}

Page 5: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

enumpublic 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

Page 6: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

Genericspublic interface List <E> { void add(E x); Iterator<E> iterator();}

public interface Iterator<E> { E next(); boolean hasNext();}

List<Integer>

public interface IntegerList { void add(Integer x); Iterator<Integer> iterator();}

List<String>

public interface StringList { void add(String x); Iterator<String> iterator();}

List<List<Integer>>

public interface ListList { void add(List<Integer> x); Iterator<List<Integer>> iterator();}

Page 7: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

GenericsAk String je podtyp Object, aký je vzťah List(String) a List(Object) ?

List<String> ls = new ArrayList<String>();List<Object> lo = ls;

List(String) nie je podtyp List(Object) !!!

lo.add(new Object()); String s = ls.get(0);

Page 8: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

Genericspublic 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();

Page 9: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

Genericsvoid 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);}

void printCollection(Collection<?> c) { for (Object e : c) System.out.println(e);}

Collection<Object> nie je supertype Collections

Page 10: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

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!

}

Page 11: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

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);

Page 12: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

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(")"); }

Page 13: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

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(); }

Page 14: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

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);

Page 15: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

Volanie metódypublic 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; }

Page 16: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

Dnes bude

• concurrency vs. parallelism• threads alias processes• synchronizácia• kritická sekcia• deadlock• komunikácia (cez pipes)

Page 17: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

Inšpirácia

• http://www.doc.ic.ac.uk/~jnm/book/book_applets/concurrency.html

Page 18: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

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

package java.lang.Thread

• new Thread() alebo jeho subclass

• metóda run()

#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; j++) {

double gg = 0-Math.PI+j+j-j+Math.PI; }

if(--countDown == 0) return;

}

}

Page 19: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

Uvoľnenie threadupublic class YieldingThread extends Thread { private int countDown = 5; private static int threadCount = 0; public YieldingThread() { super("" + ++threadCount); start(); } public String toString() {... } public void run() { while(true) { System.out.println(this); if(--countDown == 0) return; yield(); } } public static void main(String[] args) { for(int i = 0; i < 5; i++) new YieldingThread(); }}

#1: 5#2: 5#3: 5#4: 5#5: 5#1: 4#2: 4#3: 4#4: 4#5: 4#1: 3#2: 3#3: 3#4: 3#5: 3#1: 2#2: 2#3: 2#4: 2#5: 2#1: 1#2: 1#3: 1#4: 1#5: 1

• yield() – daj šancu iným

Page 20: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

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

MAX_PRIORITY MIN_PRIORITY NORM_PRIORITYsetPriority(int newPriority) interval [1..10]

[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

Page 21: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

Uspatie threadupublic 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--

sleep(long millis) throws InterruptedException

join()   čakaj kým umre

Page 22: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

Čakanie na threadclass 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"); }}

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"); }}

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();

Prvy was interrupted. isInterrupted(): false

Strvrty completed

Druhy has awakened

Treti completed

Page 23: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

Rúryclass Sender extends Thread { private Random rand = new Random(); private PipedWriter out = new PipedWriter(); public PipedWriter getPipedWriter() { return out; } public void run() { while(true) { for(char c = 'A'; c <= 'z'; c++) { try { out.write(c); sleep(rand.nextInt(500)); } catch(Exception e) { throw new RuntimeException(e); } } } }}

class Receiver extends Thread { private PipedReader in; public Receiver(Sender sender) throws IOException { in = new PipedReader(sender.getPipedWriter()); } public void run() { try { while(true) { System.out.println("Read: " + (char)in.read()); } } catch(IOException e) { throw new RuntimeException(e); } }}

public class PipedIO { public static void main(String[] args) throws Exception { Sender sender = new Sender(); Receiver receiver = new Receiver(sender); sender.start(); receiver.start(); new Timeout(4000, "Terminated"); }}

Read: ARead: BRead: CRead: DRead: ERead: FRead: GRead: HRead: IRead: JRead: KRead: LRead: MRead: NRead: OTerminatedRead: PRead: QRead: R

Page 24: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

Guličky - threadypublic 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) {} } }}

Page 25: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

Guličky - appletpublic 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); }. . . . }

Page 26: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

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(); }}

Page 27: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

SortPanel, Canvaspublic 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]); } }}

Page 28: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

RandomSrtpublic 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; } }}

Page 29: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

Semafórypublic 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

Page 30: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

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

Page 31: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

Kritická sekciaSynchronizá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(); }

Page 32: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

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é

Page 33: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

Semafóry znovapublic 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

Page 34: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

Večerajúci filozofoviaclass 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); }}

Page 35: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

Večerajúci filozofoviaclass Philosopher extends Thread { ... public void run() { 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

23

40

1

2

3

4

Page 36: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

Večerajúci filozofoviafor (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 thinkingPhil 0 has Chopstick 0 Waiting for Chopstick 1Phil 0 eatingPhil 0 thinkingPhil 0 has Chopstick 0 Waiting for Chopstick 1Phil 0 eatingPhil 0 thinkingPhil 0 has Chopstick 0 Waiting for Chopstick 1Phil 0 eatingPhil 0 thinkingPhil 0 has Chopstick 0 Waiting for Chopstick 1Phil 0 eatingPhil 0 thinkingPhil 0 has Chopstick 0 Waiting for Chopstick 1Phil 0 eatingPhil 0 thinkingPhil 0 has Chopstick 0 Waiting for Chopstick 1Phil 1 thinkingPhil 2 thinkingPhil 3 thinkingPhil 4 thinkingPhil 1 has Chopstick 1 Waiting for Chopstick 2Phil 2 has Chopstick 2 Waiting for Chopstick 3Phil 3 has Chopstick 3 Waiting for Chopstick 4Phil 4 has Chopstick 4 Waiting for Chopstick 0

Page 37: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

Ohraničený bufferpublic 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); }

Page 38: Adresáre rekurzívne class FilterAdresara implements FilenameFilter { public boolean accept(File dir, String name) { File f = new File(dir, name); return

Budíkimport java.util.Timer;import java.util.TimerTask;

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 } } public static void main(String args[]) { new Reminder(5); System.out.println("Task scheduled."); }}

•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)

//Get the Date corresponding to 11:01:00 pm today.Calendar calendar = Calendar.getInstance();calendar.set(Calendar.HOUR_OF_DAY, 23);calendar.set(Calendar.MINUTE, 1);calendar.set(Calendar.SECOND, 0);Date time = calendar.getTime();

timer = new Timer();timer.schedule(new RemindTask(), time);