Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.time.LocalDate;
- import java.time.format.DateTimeFormatter;
- import java.text.SimpleDateFormat;
- import java.util.*;
- public class ThreadTest {
- /*skapa instans av Television*/
- TelevisionStation tv;
- public ThreadTest() {
- tv = new TelevisionStation();
- /*skapa instans av 2 tråder */
- Thread th1 = new MyThread1();
- Thread th2 = new MyThread2();
- th1.start();
- th2.start();
- try {
- Thread.sleep(12000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- Thread th3 = new MyThread1();
- th3.start();
- }
- public static void main(String[] args) {
- new ThreadTest();
- }
- /*skapa två olika tråd som ska köra instans av TelevisionStation*/
- /*tråd 1: instan av TelevisionStation anropa metoder teleprompter*/
- class MyThread1 extends Thread {
- @Override
- public void run() {
- tv.showTeleprompter();
- System.out.println("Första tråd kör färdig");
- }
- }
- /*tråden skapar parametra for metoder addHeadline med hjälp av rand funktion*/
- class MyThread2 extends Thread {
- @SuppressWarnings("deprecation")
- @Override
- public void run() {
- Random rand = new Random();
- for (int i = 0; i < 200; i++) {
- tv.addHeadline(new Date(2014, rand.nextInt(12), rand.nextInt(27)), "abcdefgh" + i);
- }
- System.out.println("Andra Tråd kör färdig ");
- }
- }
- }
- class TelevisionStation extends MediaCompany {
- private final static SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy-MM-dd");
- /* Väljer att ändra från HashMap till LinkedHashMap för att få till ordningen på värden som läggs in. */
- public Map<String, Collection<String>> headlines = new LinkedHashMap<>();
- public TelevisionStation() {
- Timer timer = new Timer();
- timer.schedule(new TimerTask() {
- public void run() {
- if (headlines.size() > 100) {
- System.out.println("Size of headlines too large: " +
- headlines.size());
- }
- }
- }, 10_000, 10_000);
- }
- /* Här smiter referensen headlines till en abstrakt metod.*/
- public void showTeleprompter() {
- printHeadlines(headlines.values());
- }
- public void addHeadline(Date date, String line) {
- String day = dayFormat.format(date);
- Collection<String> lines = headlines.get(day);
- if (lines == null) {
- lines = new ArrayList<String>();
- headlines.put(day, lines);
- }
- lines.add(line);
- }
- }
- abstract class MediaCompany {
- public void printHeadlines(Collection<Collection<String>> headlines) {
- for (Collection<String> headline : headlines) {
- for (String line : headline) {
- System.out.println(line);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement