diff --git a/src/de/dhbwka/java/exercise/threads/DancingText.java b/src/de/dhbwka/java/exercise/threads/DancingText.java new file mode 100644 index 0000000..e2a1316 --- /dev/null +++ b/src/de/dhbwka/java/exercise/threads/DancingText.java @@ -0,0 +1,91 @@ +package de.dhbwka.java.exercise.threads; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.util.Random; + +import javax.swing.JComponent; +import javax.swing.JFrame; + +/** + * Part of lectures on 'Programming in Java'. Baden-Wuerttemberg + * Cooperative State University. + * + * (C) 2016-2018 by W. Geiger, T. Schlachter, C. Schmitt, W. Suess + * + * @author DHBW lecturer + * @version 1.1-NO-DANCE + */ +@SuppressWarnings( "serial" ) +public class DancingText extends JComponent { + + private final static int XBASE = 30; + private final static int XSTEP = 36; + private final static int YBASE = 150; + private final static Random RANDOM = new Random(); + + private String text; + private final long delay; + + private int colR = 0; // Color-Channel: red + private int colG = 90; // Color-Channel: green + private int colB = 180; // Color-Channel: blue + private int yOffset = 0; + + public DancingText( String text, long delay ) { + this.text = text; + this.delay = delay; + + Thread t = new Thread() { + @Override + public void run() { + while ( true ) { + DancingText.this.repaint(); + try { + Thread.sleep( DancingText.this.delay ); + } catch ( InterruptedException e ) { + e.printStackTrace(); + } + } + } + }; + + t.setDaemon( true ); + t.start(); + } + + /** + * Paint dancing text on Graphics + * + * @param g + * graphics to use + */ + @Override + public void paintComponent( Graphics g ) { + super.paintComponent( g ); + g.setFont( new Font( "Helvetica", Font.BOLD, 48 ) ); + for ( int i = 0; i < this.text.length(); i++ ) { + char c = this.text.charAt( i ); + + this.colR = (this.colR + 4 + DancingText.RANDOM.nextInt( 4 )) % 256; + this.colG = (this.colG + 4 + DancingText.RANDOM.nextInt( 4 )) % 256; + this.colB = (this.colB + 4 + DancingText.RANDOM.nextInt( 4 )) % 256; + + this.yOffset = DancingText.RANDOM.nextInt( 30 ); + + g.setColor( new Color( this.colR, this.colG, this.colB ) ); + g.drawString( "" + c, DancingText.XBASE + i * DancingText.XSTEP, + DancingText.YBASE - this.yOffset ); + } + } + + public static void main( String[] args ) { + // Create frame and add DancingText component + JFrame f = new JFrame( "Dancing Text" ); + f.add( new DancingText( "Dancing Text :-)", 200 ) ); + f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); + f.setSize( 640, 280 ); + f.setVisible( true ); + } +} diff --git a/src/de/dhbwka/java/exercise/threads/TrafficLight.java b/src/de/dhbwka/java/exercise/threads/TrafficLight.java new file mode 100644 index 0000000..298c8d7 --- /dev/null +++ b/src/de/dhbwka/java/exercise/threads/TrafficLight.java @@ -0,0 +1,146 @@ +package de.dhbwka.java.exercise.threads; + +import java.awt.Color; +import java.awt.Graphics; + +import javax.swing.JComponent; +import javax.swing.JFrame; + +class LightPhase { + private String name; + private boolean red; + private boolean yellow; + private boolean green; + private int duration; + private int next; + + public LightPhase(String name, boolean red, boolean yellow, boolean green, int duration, int next) { + this.name = name; + this.red = red; + this.yellow = yellow; + this.green = green; + this.duration = duration; + this.next = next; + } + + public LightPhase getNext() { + return LightPhases[next]; + } + + public String getName() { + return name; + } + + public boolean isRed() { + return red; + } + + public boolean isYellow() { + return yellow; + } + + public boolean isGreen() { + return green; + } + + public int getDuration() { + return duration; + } + + private final static LightPhase LightPhases[] = { + new LightPhase("Red", true, false, false, 500, 1), + new LightPhase("Red+Yellow", true, true, false, 200, 2), + new LightPhase("Green", false, false, true, 500, 3), + new LightPhase("Yellow", false, true, false, 200, 0) + }; + + public static LightPhase[] getLightPhases() { + return LightPhases; + } +} + +/** + * Part of lectures on 'Programming in Java'. Baden-Wuerttemberg + * Cooperative State University. + * + * (C) 2016-2018 by W. Geiger, T. Schlachter, C. Schmitt, W. Suess + * + * @author DHBW lecturer + * @version 1.1-STATICLIGHT + */ +@SuppressWarnings("serial") +public class TrafficLight extends JComponent { + private final static long DELAY = 500; + + LightPhase currentPhase = LightPhase.getLightPhases()[0]; + + public TrafficLight() { + Thread t = new Thread() { + @Override + public void run() { + while (true) { + repaint(); + try { + Thread.sleep(currentPhase.getDuration()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + currentPhase = currentPhase.getNext(); + } + } + }; + t.setDaemon(true); + t.start(); + } + + @Override + public void paintComponent(Graphics g) { + super.paintComponent(g); + + // traffic light box + g.setColor(Color.BLACK); + g.fillRect(10, 10, 80, 195); + + // 3 x empty light + g.setColor(Color.WHITE); + g.fillOval(23, 23, 54, 54); + g.fillOval(23, 83, 54, 54); + g.fillOval(23, 143, 54, 54); + + /* + * ==================================================== + * ==================================================== + * SET THE CORRECT VALUES FOR THE FOLLOWING 3 VARIABLES + * ==================================================== + * ==================================================== + */ + boolean redOn = currentPhase.isRed(); + boolean yellowOn = currentPhase.isYellow(); + boolean greenOn = currentPhase.isGreen(); + + // draw colored lights, if active + if (redOn) { + g.setColor(Color.RED); + g.fillOval(25, 25, 50, 50); + } + + if (yellowOn) { + g.setColor(Color.YELLOW); + g.fillOval(25, 85, 50, 50); + } + if (greenOn) { + g.setColor(Color.GREEN); + g.fillOval(25, 145, 50, 50); + } + } + + public static void main(String[] args) { + // Create frame and add TrafficLight component + JFrame f = new JFrame("Traffic Light"); + f.add(new TrafficLight()); + f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + f.setSize(100, 260); + f.setVisible(true); + } + +} diff --git a/src/de/dhbwka/java/exercise/threads/buffer/MyBuffer.java b/src/de/dhbwka/java/exercise/threads/buffer/MyBuffer.java new file mode 100644 index 0000000..343b33a --- /dev/null +++ b/src/de/dhbwka/java/exercise/threads/buffer/MyBuffer.java @@ -0,0 +1,97 @@ +package de.dhbwka.java.exercise.threads.buffer; + +import java.util.LinkedList; + +public class MyBuffer { + LinkedList buffer; + static final int MAX_SIZE = 10; + + public MyBuffer() { + buffer = new LinkedList<>(); + } + + public synchronized void put(int value) throws InterruptedException { + while (buffer.size() >= MAX_SIZE) { + wait(); // Wait until space is available + } + buffer.add(value); + System.out.println("Produced: " + value); + notifyAll(); // Notify consumers that an item has been added + } + + public synchronized int get() throws InterruptedException { + while (buffer.isEmpty()) { + wait(); // Wait until an item is available + } + int value = buffer.removeFirst(); + System.out.println("Consumed: " + value); + notifyAll(); // Notify producers that space is available + return value; + } + + public synchronized int size() { + return buffer.size(); + } +} + +class Producer extends Thread { + private MyBuffer buffer; + + public Producer(MyBuffer buffer) { + this.buffer = buffer; + } + + @Override + public void run() { + try { + for (int i = 0; i < 20; i++) { + buffer.put(i); + Thread.sleep((long) (Math.random() * 1000)); + System.out.println("Produced: " + i); + System.out.println("Buffer size: " + buffer.size()); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } +} + +class Consumer extends Thread { + private MyBuffer buffer; + + public Consumer(MyBuffer buffer) { + this.buffer = buffer; + } + + @Override + public void run() { + try { + for (int i = 0; i < 20; i++) { + int value = buffer.get(); + Thread.sleep((long) (Math.random() * 1000)); + System.out.println("Processed: " + value); + System.out.println("Buffer size: " + buffer.size()); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } +} + +class Runner { + public static void main(String[] args) { + MyBuffer buffer = new MyBuffer(); + Producer producer = new Producer(buffer); + Consumer consumer = new Consumer(buffer); + + producer.start(); + consumer.start(); + + try { + producer.join(); + consumer.join(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } +} diff --git a/src/de/dhbwka/java/exercise/threads/search/SearchEngine.java b/src/de/dhbwka/java/exercise/threads/search/SearchEngine.java new file mode 100644 index 0000000..d35da83 --- /dev/null +++ b/src/de/dhbwka/java/exercise/threads/search/SearchEngine.java @@ -0,0 +1,95 @@ +package de.dhbwka.java.exercise.threads.search; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URI; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class SearchEngine { + private static final int MAX_THREADS = 3; + private List running_loaders = new ArrayList<>(); + private static final String file = "src/de/dhbwka/java/exercise/threads/search/uri.txt"; + + public SearchEngine() throws InterruptedException { + try (BufferedReader br = new BufferedReader(new FileReader(file))) { + Iterator lines = br.lines().iterator(); + while (running_loaders.size() > 0 || lines.hasNext()) { + if (running_loaders.size() < MAX_THREADS && lines.hasNext()) { + String line = lines.next(); + PageLoader pl = new PageLoader(line, "UTF-8"); + Thread plThread = new Thread(pl); + System.out.println("Loading " + line); + plThread.start(); + running_loaders.add(pl); + } + + List toRemove = new ArrayList<>(); + for (PageLoader pl : this.running_loaders) { + if (pl != null && pl.pageLoaded()) { + System.out.println( + "Page " + pl.getUrl() + " loaded: " + pl.getPageContent().replaceAll("\n", "##").substring(0, 40)); + toRemove.add(pl); + } + } + running_loaders.removeAll(toRemove); + + Thread.sleep(100); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void main(String[] args) throws InterruptedException { + new SearchEngine(); + } +} + +class PageLoader implements Runnable { + private String content; + + public synchronized boolean pageLoaded() { + return content != null; + } + + public synchronized String getPageContent() { + if (!pageLoaded()) + throw new Error("Page not loaded"); + return content; + } + + public static String getStringContentFromUrl(String url, String encoding) { + StringBuilder buffer = new StringBuilder(); + String line = null; + try (BufferedReader br = new BufferedReader( + new InputStreamReader( + new URI(url).toURL().openStream(), encoding))) { + while ((line = br.readLine()) != null) { + buffer.append(line).append(System.lineSeparator()); + } + } catch (Exception ex) { + } + return buffer.toString(); + } + + private String url; + private String encoding; + + public String getUrl() { + return url; + } + + public PageLoader(String url, String encoding) { + this.url = url; + this.encoding = encoding; + } + + @Override + public void run() { + this.content = getStringContentFromUrl(url, encoding); + } +} diff --git a/src/de/dhbwka/java/exercise/threads/search/uri.txt b/src/de/dhbwka/java/exercise/threads/search/uri.txt new file mode 100644 index 0000000..98e9674 --- /dev/null +++ b/src/de/dhbwka/java/exercise/threads/search/uri.txt @@ -0,0 +1,4 @@ +https://www.tagesschau.de +https://www.sueddeutsche.de +https://www.spiegel.de +https://www.kit.edu \ No newline at end of file