Presentation is loading. Please wait.

Presentation is loading. Please wait.

Многопоточность в Java

Similar presentations


Presentation on theme: "Многопоточность в Java"— Presentation transcript:

1 Многопоточность в Java
Макаревич Л. Г.

2 Понятие потока Поток – это одна из веточек вычислительного процесса. Каждый поток выполняет свои действия в пределах одного приложения

3 Calendar calendar = Calendar.getInstance();
import 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 timer thread public static void main(String args[]) { System.out.println("About to schedule task."); new Reminder(5); new Reminder(10); System.out.println("Task scheduled."); 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);

4 Будильник import java.util.TimerTask; import java.awt.Toolkit;
public class ReminderBeep { Toolkit toolkit; Timer timer; public ReminderBeep(int seconds) { toolkit = Toolkit.getDefaultToolkit(); timer = new Timer(); timer.schedule(new RemindTask(), seconds*1000); } class RemindTask extends TimerTask { public void run() { System.out.println("Time's up!"); toolkit.beep(); //timer.cancel(); //Not necessary because we call System.exit System.exit(0); //Stops the AWT thread (and everything else) public static void main(String args[]) { System.out.println("About to schedule task."); new ReminderBeep(5); System.out.println("Task scheduled."); Будильник

5 Создание потоков Наследование от класс Thread
Реализация интерфейса Runnable

6 Поток наследует от Thread
public class SimpleThread extends Thread { public SimpleThread(String str) { super(str); } public void run() { for (int i = 0; i < 10; i++) { System.out.println(i + " " + getName()); try { sleep((long)(Math.random() * 1000)); } catch (InterruptedException e) {} System.out.println("DONE! " + getName()); public static void main(String[] args) { SimpleThread [] p = new SimpleThread[5]; for ( int i = 0; i < 5; i++) p[i] = new SimpleThread("Thread "+i); p[i].start();

7 Поток с интерфейсом Runnable
public class RunnableThread implements Runnable { Thread t; public RunnableThread(String str) { t = new Thread(this,str); } public void run() { for (int i = 0; i < 10; i++) { System.out.println(i + " " + t.getName()); try { Thread.sleep((long)(Math.random() * 1000)); } catch (InterruptedException e) {} System.out.println("DONE! " + t.getName()); public static void main(String[] args) { RunnableThread [] p = new RunnableThread[5]; for ( int i = 0; i < 5; i++) p[i] = new RunnableThread("Thread "+i); p[i].t.start();

8 Часики import java.awt.Graphics; import java.util.*;
import java.text.DateFormat; import java.applet.Applet; public class Clock extends Applet implements Runnable { private Thread clockThread = null; public void start() { if (clockThread == null) { clockThread = new Thread(this, "Clock"); clockThread.start(); } public void run() { Thread myThread = Thread.currentThread(); while (clockThread == myThread) { repaint(); try { Thread.sleep(1000); } catch (InterruptedException e){ public void paint(Graphics g) { // get the time and convert it to a date Calendar cal = Calendar.getInstance(); Date date = cal.getTime(); // format it and display it DateFormat dateFormatter = DateFormat.getTimeInstance(); g.drawString(dateFormatter.format(date), 5, 10); // overrides Applet's stop method, not Thread's public void stop() { clockThread = null; Часики

9 Жизненный цикл потока Its sleep method is invoked.
The thread calls the wait method to wait for a specific condition to be satisifed. The thread is blocking on I/O.

10 Приоритеты потоков MAX_PRIORITY (10) NORM_PRIORITY (5)
MIN_PRIORITY (1) setPriority(int); int getPriority();

11 Основной поток Thread t = Thread.currentThread(); join();
boolean isAlive(); public class RunnableThread implements Runnable { Thread t; public RunnableThread(String str) { t = new Thread(this,str); } public void run() { for (int i = 0; i < 10; i++) { System.out.println(i + " " + t.getName()); try { Thread.sleep((long)(Math.random() * 1000)); } catch (InterruptedException e) {} System.out.println("DONE! " + t.getName()); public static void main(String[] args) { RunnableThread [] p = new RunnableThread[5]; for ( int i = 0; i < 5; i++) p[i] = new RunnableThread("Thread "+i); p[i].t.start(); try{ p[i].t.join(); }catch(InterruptedException e){} System.out.println( "Finished");

12 Демон-потоки Демон-потоки позволяют описывать фоновые процессы, которые нужны только для обслуживания основных потоков выполнения и не могут существовать без них. Для работы с этим свойством существуют методы setDaemon() и isDaemon(). class Demon implements Runnable { String name; Demon(String s){name = s;} Thread t = new Thread(this); public void run() for ( int i = 0; i <100; i++) try{ Thread.sleep(500); }catch(Exception e){} System.out.println(name + i); } public static void main(String[] args) Demon d[] = new Demon[5]; for ( int i = 0 ; i < 5; i++ ) d[i] = new Demon("Thread"+i); // d[i].t.setDaemon(true); d[i].t.start();

13 Синхронизация public class Producer extends Thread {
private CubbyHole cubbyhole; private int number; public Producer(CubbyHole c, int number) { cubbyhole = c; this.number = number; } public void run() { for (int i = 0; i < 10; i++) { cubbyhole.put(i); System.out.println("Producer #" + this.number + " put: " + i); try { sleep((int)(Math.random() * 100)); } catch (InterruptedException e) { } public class Consumer extends Thread { private CubbyHole cubbyhole; private int number; public Consumer(CubbyHole c, int number) { cubbyhole = c; this.number = number; } public void run() { int value = 0; for (int i = 0; i < 10; i++) { value = cubbyhole.get(); System.out.println("Consumer #" + this.number + " got: " + value); Producer #1 put: 0 Consumer #1 got: 0 Producer #1 put: 1 Consumer #1 got: 1 Producer #1 put: 2 Consumer #1 got: 2 Producer #1 put: 3 Consumer #1 got: 3 Producer #1 put: 4 Consumer #1 got: 4 Producer #1 put: 5 Consumer #1 got: 5 Producer #1 put: 6 Consumer #1 got: 6 Producer #1 put: 7 Consumer #1 got: 7 Producer #1 put: 8 Consumer #1 got: 8 Producer #1 put: 9 Consumer #1 got: 9 public class CubbyHole { private int contents; public int get() { return contents; } public void put(int value) { contents = value; public class ProducerConsumerTest { public static void main(String[] args) { CubbyHole c = new CubbyHole(); Producer p1 = new Producer(c, 1); Consumer c1 = new Consumer(c, 1); p1.start(); c1.start(); }

14 Использование synchronized методов
public class CubbyHole { private int contents; private boolean available = false; public synchronized int get() { if (available == true) { available = false; return contents;} } public void synchronized put(int value) { if (available == false) { available = true; contents = value; } public class CubbyHole { private int contents; private boolean available = false; public synchronized int get() { while (available == false) { try { wait(); } catch (InterruptedException e) { } } available = false; notifyAll(); return contents; public synchronized void put(int value) { while (available == true) { contents = value; available = true; Критическая секция

15 Object protected  Object clone()           Creates and returns a copy of this object.  boolean equals(Object obj)           Indicates whether some other object is "equal to" this one. protected  void finalize()           Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.  Class getClass()           Returns the runtime class of an object.  int hashCode()           Returns a hash code value for the object.  void notify()           Wakes up a single thread that is waiting on this object's monitor. notifyAll()           Wakes up all threads that are waiting on this object's monitor.  String toString()           Returns a string representation of the object. wait()           Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. wait(long timeout)           Causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. wait(long timeout, int nanos)           Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

16 class Caller implements Runnable { String msg; Callme target;
class Callme { synchronized void call(String msg) System.out.print("["+msg); try Thread.sleep(1000); }catch(Exception e ) {System.out.println("Прерывание");} System.out.println("]"); } class Demo { public static void main(String [] arg) Callme target = new Callme(); Caller o1 = new Caller(target,"Hello"); Caller o2 = new Caller(target,"Good morning"); Caller o3 = new Caller(target,"Bye"); Callme tt = new Callme(); Caller o11 = new Caller(tt,"HHH"); Caller o12 = new Caller(tt,"GGGG"); Caller o13 = new Caller(tt,"BBBB"); } /* [Hello[Good morning[Bye] ] */ /*2) [Hello] [Good morning] [Bye] class Caller implements Runnable { String msg; Callme target; Thread t; public Caller(Callme targ, String s) target = targ; msg = s; t = new Thread(this); t.start(); } public void run() target.call(msg);

17 class Caller implements Runnable { String msg; Callme target;
class Callme { void call(String msg) System.out.print("["+msg); try Thread.sleep(1000); }catch(Exception e ) {System.out.println("Прерывание");} System.out.println("]"); } class Demo { public static void main(String [] arg) Callme target = new Callme(); Caller o1 = new Caller(target,"Hello"); Caller o2 = new Caller(target,"Good morning"); Caller o3 = new Caller(target,"Bye"); } /*[Hello] [Good morning] [Bye] */ class Caller implements Runnable { String msg; Callme target; Thread t; public Caller(Callme targ, String s) target = targ; msg = s; t = new Thread(this); t.start(); } public void run() synchronized(target) { target.call(msg);

18 Приостановка и возобновление потоков
class T1 implements Runnable { boolean flag = false; String name; T1(String n){name = n; Thread t1 = new Thread(this,n); t1.start();flag = false;} public void run() try for ( int i = 0; i < 20; i++ ) System.out.println(name + " " + i); Thread.sleep(100); synchronized(this) { while(flag){ wait();}} } catch(Exception e){} System.out.println(name + " " + "End"); void mysuspend() flag = true; synchronized void myresume() { flag = false; notify(); public static void main(String [] a ) T1 t11 = new T1 (" "); t11.mysuspend(); T1 t12 = new T1 (" "); try { Thread.sleep(20000);} catch(Exception e){} t11.myresume(); void resume() Deprecated void stop() void suspend()

19 public synchronized void mousePressed(MouseEvent e) {
e.consume(); System.out.println("mousePressed"); threadSuspended = !threadSuspended; if (!threadSuspended) notifyAll(); } public void run() { int w = getSize().width; while (!done) { try { Thread.currentThread().sleep(interval); synchronized(this) { while (threadSuspended) wait(); } catch (InterruptedException canthappen) { // Do nothing if (offset++ > w) offset = 0; repaint();

20 Поток с использованием внутреннего класса
public class ThreadsDemo3 { String mesg; Thread t; int count; public static void main(String[] argv) { new ThreadsDemo3("Hello from X", 10); new ThreadsDemo3("Hello from Y", 15); } public ThreadsDemo3(String m, int n) { count = n; mesg = m; t = new Thread(new Runnable() { public void run() { while (count-- > 0) { println(mesg); try { Thread.sleep(100); // 100 msec } catch (InterruptedException e) {return;} System.out.println (mesg + " thread all done."); }}); t.setName(m + " runner Thread"); t.start(); } }

21 Пример с анимацией в потоках
import java.applet.*; import java.awt.*; import java.util.*; public class Animator extends Applet implements Runnable { int x; int y; boolean done; public void start() { done = false; new Thread(this).start(); } public void stop() { done = true; } public synchronized void run() { int width = getSize().width; // Get the framesize int height = getSize().height; x = (int)(Math.random() * width); y = (int)(Math.random() * height); while (!done) { width = getSize().width; height = getSize().height; // Did we go off the deep end? :-) if (x++ >= width) x=0; // return to shallow end if (y++ >= height) y=0; repaint(); // Tell AWT to call our paint(). try { Thread.sleep(250); } catch (InterruptedException e) {return;} Пример с анимацией в потоках public void paint(Graphics g) { g.setColor(Color.red); g.fillRect(x, y, 10, 10); }

22


Download ppt "Многопоточность в Java"

Similar presentations


Ads by Google