//Metode 1 interface Runnable { //Oppgaver som en tr?d skal utf?re m? v?re objekter av grensesnittet Runnable void run(); } class MyTask implements Runnable { /* Say hello, but think for a while between each time. */ public void run() { for (int i = 1; i < 5000; i++) if (i % 1000 == 0) System.out.printf("Hello for the %d-th time!\n", i / 1000); } } public class Main { public static void main(String[] args) { Runnable task = new MyTask(); Thread worker1 = new Thread(task); Thread worker2 = new Thread(task); worker1.start(); // Will make a call to task.run() worker2.start(); } } //Metode 2 class MyThread extends Thread { @Override public void run() { ... } } class Main { public static void main(String[] args) { Thread worker = new MyThread(); worker.start(); } } //L?ser i oppgaven tr?dene har til felles public class Main { public static void main(String[] args) { Runnable task = new MyTask(); Thread worker1 = new Thread(task); Thread worker2 = new Thread(task); worker1.start(); // Will make a call to task.run() worker2.start(); } } class MyTask implements Runnable { private final Lock lock = new ReentrantLock(); private final int MAX_COUNT = 10000; private int sharedCounter = 0; public void run() { System.out.println("Starting! Shared counter = " + sharedCounter); for (int i = 0; i < MAX_COUNT; i++) { lock.lock(); try { sharedCounter = sharedCounter + 1; } finally { lock.unlock(); } } System.out.println("Done! Shared counter = " + sharedCounter); } } //Plassere delt data i monitor import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Main { public static void main(String[] args) { CountMonitor monitor = new CountMonitor(); Runnable task = new MyTask(monitor); Thread worker1 = new Thread(task); Thread worker2 = new Thread(task); worker1.start(); worker2.start(); } } class CountMonitor { private final Lock lock = new ReentrantLock(); private int sharedCounter = 0; // The protected data. public void increment() { lock.lock(); try { sharedCounter = sharedCounter + 1; } finally { lock.unlock(); } } public int getCounter() { return sharedCounter; } } class MyTask implements Runnable { private final int MAX_COUNT = 10000; private final CountMonitor monitor; public MyTask(CountMonitor monitor) { this.monitor = monitor; } public void run() { for (int i = 0; i < MAX_COUNT; i++) { monitor.increment(); } System.out.println("Done! Shared counter = " + monitor.getCounter()); } } //Grensesnitt med tilganger interface Condition { void await(); void signal(); void signalAll(); }