詳解Java編程中線程同步和准時啟動線程的辦法。本站提示廣大學習愛好者:(詳解Java編程中線程同步和准時啟動線程的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是詳解Java編程中線程同步和准時啟動線程的辦法正文
應用wait()與notify()完成線程間協作
1. wait()與notify()/notifyAll()
挪用sleep()和yield()的時刻鎖並沒有被釋放,而挪用wait()將釋放鎖。如許另外一個義務(線程)可以取得以後對象的鎖,從而進入它的synchronized辦法中。可以經由過程notify()/notifyAll(),或許時光到期,從wait()中恢復履行。
只能在同步掌握辦法或同步塊中挪用wait()、notify()和notifyAll()。假如在非同步的辦法裡挪用這些辦法,在運轉時會拋出IllegalMonitorStateException異常。
2.模仿單個線程對多個線程的叫醒
模仿線程之間的協作。Game類有2個同步辦法prepare()和go()。標記位start用於斷定以後線程能否須要wait()。Game類的實例起首啟動一切的Athele類實例,使其進入wait()狀況,在一段時光後,轉變標記位並notifyAll()一切處於wait狀況的Athele線程。
Game.java
package concurrency; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; class Athlete implements Runnable { private final int id; private Game game; public Athlete(int id, Game game) { this.id = id; this.game = game; } public boolean equals(Object o) { if (!(o instanceof Athlete)) return false; Athlete athlete = (Athlete) o; return id == athlete.id; } public String toString() { return "Athlete<" + id + ">"; } public int hashCode() { return new Integer(id).hashCode(); } public void run() { try { game.prepare(this); } catch (InterruptedException e) { System.out.println(this + " quit the game"); } } } public class Game implements Runnable { private Set<Athlete> players = new HashSet<Athlete>(); private boolean start = false; public void addPlayer(Athlete one) { players.add(one); } public void removePlayer(Athlete one) { players.remove(one); } public Collection<Athlete> getPlayers() { return Collections.unmodifiableSet(players); } public void prepare(Athlete athlete) throws InterruptedException { System.out.println(athlete + " ready!"); synchronized (this) { while (!start) wait(); if (start) System.out.println(athlete + " go!"); } } public synchronized void go() { notifyAll(); } public void ready() { Iterator<Athlete> iter = getPlayers().iterator(); while (iter.hasNext()) new Thread(iter.next()).start(); } public void run() { start = false; System.out.println("Ready......"); System.out.println("Ready......"); System.out.println("Ready......"); ready(); start = true; System.out.println("Go!"); go(); } public static void main(String[] args) { Game game = new Game(); for (int i = 0; i < 10; i++) game.addPlayer(new Athlete(i, game)); new Thread(game).start(); } }
成果:
Ready...... Ready...... Ready...... Athlete<0> ready! Athlete<1> ready! Athlete<2> ready! Athlete<3> ready! Athlete<4> ready! Athlete<5> ready! Athlete<6> ready! Athlete<7> ready! Athlete<8> ready! Athlete<9> ready! Go! Athlete<9> go! Athlete<8> go! Athlete<7> go! Athlete<6> go! Athlete<5> go! Athlete<4> go! Athlete<3> go! Athlete<2> go! Athlete<1> go! Athlete<0> go!
3.模仿忙期待進程
MyObject類的實例是被不雅察者,當不雅察事宜產生時,它會告訴一個Monitor類的實例(告訴的方法是轉變一個標記位)。而此Monitor類的實例是經由過程忙期待來赓續的檢討標記位能否變更。
BusyWaiting.java
import java.util.concurrent.TimeUnit; class MyObject implements Runnable { private Monitor monitor; public MyObject(Monitor monitor) { this.monitor = monitor; } public void run() { try { TimeUnit.SECONDS.sleep(3); System.out.println("i'm going."); monitor.gotMessage(); } catch (InterruptedException e) { e.printStackTrace(); } } } class Monitor implements Runnable { private volatile boolean go = false; public void gotMessage() throws InterruptedException { go = true; } public void watching() { while (go == false) ; System.out.println("He has gone."); } public void run() { watching(); } } public class BusyWaiting { public static void main(String[] args) { Monitor monitor = new Monitor(); MyObject o = new MyObject(monitor); new Thread(o).start(); new Thread(monitor).start(); } }
成果:
i'm going. He has gone.
4.應用wait()與notify()改寫下面的例子
上面的例子經由過程wait()來代替忙期待機制,當收到告訴新聞時,notify以後Monitor類線程。
Wait.java
package concurrency.wait; import java.util.concurrent.TimeUnit; class MyObject implements Runnable { private Monitor monitor; public MyObject(Monitor monitor) { this.monitor = monitor; }
准時啟動線程
這裡供給兩種在指准時間後啟動線程的辦法。一是經由過程java.util.concurrent.DelayQueue完成;二是經由過程java.util.concurrent.ScheduledThreadPoolExecutor完成。
1. java.util.concurrent.DelayQueue
類DelayQueue是一個無界壅塞隊列,只要在延遲期滿時能力從中提取元素。它接收完成Delayed接口的實例作為元素。
<<interface>>Delayed.java
package java.util.concurrent; import java.util.*; public interface Delayed extends Comparable<Delayed> { long getDelay(TimeUnit unit); }
getDelay()前往與此對象相干的殘剩延遲時光,以給定的時光單元表現。此接口的完成必需界說一個 compareTo 辦法,該辦法供給與此接口的 getDelay 辦法分歧的排序。
DelayQueue隊列的頭部是延遲期滿後保留時光最長的 Delayed 元素。當一個元素的getDelay(TimeUnit.NANOSECONDS) 辦法前往一個小於等於 0 的值時,將產生到期。
2.設計帶有時光延遲特征的隊列
類DelayedTasker保護一個DelayQueue<DelayedTask> queue,個中DelayedTask完成了Delayed接口,並由一個外部類界說。內部類和外部類都完成Runnable接口,關於內部類來講,它的run辦法是按界說的時光前後掏出隊列中的義務,而這些義務即外部類的實例,外部類的run辦法界說每一個線程詳細邏輯。
這個設計的本質是界說了一個具有時光特征的線程義務列表,並且該列表可所以隨意率性長度的。每次添加義務時指定啟動時光便可。
DelayedTasker.java
package com.zj.timedtask; import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; import java.util.Collection; import java.util.Collections; import java.util.Random; import java.util.concurrent.DelayQueue; import java.util.concurrent.Delayed; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class DelayedTasker implements Runnable { DelayQueue<DelayedTask> queue = new DelayQueue<DelayedTask>(); public void addTask(DelayedTask e) { queue.put(e); } public void removeTask() { queue.poll(); } public Collection<DelayedTask> getAllTasks() { return Collections.unmodifiableCollection(queue); } public int getTaskQuantity() { return queue.size(); } public void run() { while (!queue.isEmpty()) try { queue.take().run(); } catch (InterruptedException e) { System.out.println("Interrupted"); } System.out.println("Finished DelayedTask"); } public static class DelayedTask implements Delayed, Runnable { private static int counter = 0; private final int id = counter++; private final int delta; private final long trigger; public DelayedTask(int delayInSeconds) { delta = delayInSeconds; trigger = System.nanoTime() + NANOSECONDS.convert(delta, SECONDS); } public long getDelay(TimeUnit unit) { return unit.convert(trigger - System.nanoTime(), NANOSECONDS); } public int compareTo(Delayed arg) { DelayedTask that = (DelayedTask) arg; if (trigger < that.trigger) return -1; if (trigger > that.trigger) return 1; return 0; } public void run() { //run all that you want to do System.out.println(this); } public String toString() { return "[" + delta + "s]" + "Task" + id; } } public static void main(String[] args) { Random rand = new Random(); ExecutorService exec = Executors.newCachedThreadPool(); DelayedTasker tasker = new DelayedTasker(); for (int i = 0; i < 10; i++) tasker.addTask(new DelayedTask(rand.nextInt(5))); exec.execute(tasker); exec.shutdown(); } }
成果:
[0s]Task 1 [0s]Task 2 [0s]Task 3 [1s]Task 6 [2s]Task 5 [3s]Task 8 [4s]Task 0 [4s]Task 4 [4s]Task 7 [4s]Task 9 Finished DelayedTask
3. java.util.concurrent.ScheduledThreadPoolExecutor
該類可以另行支配在給定的延遲後運轉義務(線程),或許按期(反復)履行義務。在結構子中須要曉得線程池的年夜小。最重要的辦法是:
[1] schedule
public ScheduledFuture<?> schedule(Runnable command, long delay,TimeUnit unit)
創立並履行在給定延遲後啟用的一次性操作。
指定者:
-接口 ScheduledExecutorService 中的 schedule;
參數:
-command - 要履行的義務 ;
-delay - 從如今開端延遲履行的時光 ;
-unit - 延遲參數的時光單元 ;
前往:
-表現掛起義務完成的 ScheduledFuture,而且其 get() 辦法在完成後將前往 null。
[2] scheduleAtFixedRate
public ScheduledFuture<?> scheduleAtFixedRate(
Runnable command,long initialDelay,long period,TimeUnit unit)
創立並履行一個在給定初始延遲後初次啟用的按期操作,後續操作具有給定的周期;也就是將在 initialDelay 後開端履行,然後在 initialDelay+period 後履行,接著在 initialDelay + 2 * period 後履行,依此類推。假如義務的任何一個履行碰到異常,則後續履行都邑被撤消。不然,只能經由過程履行法式的撤消或終止辦法來終止該義務。假如此義務的任何一個履行要消費比其周期更長的時光,則將推延後續履行,但不會同時履行。
指定者:
-接口 ScheduledExecutorService 中的 scheduleAtFixedRate;
參數:
-command - 要履行的義務 ;
-initialDelay - 初次履行的延遲時光 ;
-period - 持續履行之間的周期 ;
-unit - initialDelay 和 period 參數的時光單元 ;
前往:
-表現掛起義務完成的 ScheduledFuture,而且其 get() 辦法在撤消後將拋出異常。
4.設計帶有時光延遲特征的線程履行者
類ScheduleTasked聯系關系一個ScheduledThreadPoolExcutor,可以指定線程池的年夜小。經由過程schedule辦法曉得線程及延遲的時光,經由過程shutdown辦法封閉線程池。關於詳細義務(線程)的邏輯具有必定的靈巧性(比擬前一中設計,前一種設計必需事前界說線程的邏輯,但可以經由過程繼續或裝潢修正線程詳細邏輯設計)。
ScheduleTasker.java
package com.zj.timedtask; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ScheduleTasker { private int corePoolSize = 10; ScheduledThreadPoolExecutor scheduler; public ScheduleTasker() { scheduler = new ScheduledThreadPoolExecutor(corePoolSize); } public ScheduleTasker(int quantity) { corePoolSize = quantity; scheduler = new ScheduledThreadPoolExecutor(corePoolSize); } public void schedule(Runnable event, long delay) { scheduler.schedule(event, delay, TimeUnit.SECONDS); } public void shutdown() { scheduler.shutdown(); } public static void main(String[] args) { ScheduleTasker tasker = new ScheduleTasker(); tasker.schedule(new Runnable() { public void run() { System.out.println("[1s]Task 1"); } }, 1); tasker.schedule(new Runnable() { public void run() { System.out.println("[2s]Task 2"); } }, 2); tasker.schedule(new Runnable() { public void run() { System.out.println("[4s]Task 3"); } }, 4); tasker.schedule(new Runnable() { public void run() { System.out.println("[10s]Task 4"); } }, 10); tasker.shutdown(); } }
成果:
[1s]Task 1 [2s]Task 2 [4s]Task 3 [10s]Task 4 public void run() { try { TimeUnit.SECONDS.sleep(3); System.out.println("i'm going."); monitor.gotMessage(); } catch (InterruptedException e) { e.printStackTrace(); } } }
class Monitor implements Runnable { private volatile boolean go = false; public synchronized void gotMessage() throws InterruptedException { go = true; notify(); } public synchronized void watching() throws InterruptedException { while (go == false) wait(); System.out.println("He has gone."); } public void run() { try { watching(); } catch (InterruptedException e) { e.printStackTrace(); } } } public class Wait { public static void main(String[] args) { Monitor monitor = new Monitor(); MyObject o = new MyObject(monitor); new Thread(o).start(); new Thread(monitor).start(); } }
成果:
i'm going. He has gone.