java多线程
//Player.java package com.unit.test; public class Player implements Runnable { private final int id; private Game game; public Player(int id, Game game) { this.id = id; this.game = game; } @Override public String toString() { return "Athlete<" + id + ">"; } public int hashCode() { return new Integer(id).hashCode(); } public void playGame() throws InterruptedException{ System.out.println(this.toString() + " ready!"); game.play(this); } public void run() { try { playGame(); } catch (InterruptedException e) { System.out.println(this + " quit the game"); } } }
//Game.java public class Game implements Runnable { private boolean start = false; @Override public String toString() { return "Game"; } public synchronized void play(Player player) { try { while (!start) { System.out.println(player + " wait..."); wait(); } } catch (Exception e) { System.out.println("sleep Exception: " + e.getMessage()); } if (start) { try { Thread.sleep(5000); } catch (Exception e) { System.out.println("sleep Exception: " + e.getMessage()); } System.out.println(player + " have played!"); } } // 通知所有玩家 public synchronized void beginStart() { start = true; notifyAll(); } public void run() { start = false; System.out.println(this + " Ready......"); System.out.println(this + " start"); beginStart();// 通知所有玩家游戏准备好了 } public static void main(String[] args) { Set<Player> players = new HashSet<Player>(); // 实例化一个游戏 Game game = new Game(); // 实例化3个玩家 for (int i = 0; i < 3; i++) players.add(new Player(i, game)); // 启动3个玩家 Iterator<Player> iter = players.iterator(); while (iter.hasNext()) { new Thread(iter.next()).start(); } try { System.out.println("main Thread sleep ..."); Thread.sleep(10000); System.out.println("main Thread wake up"); } catch (Exception e) { System.out.println("sleep Exception: " + e.getMessage()); } // 游戏启动 new Thread(game).start(); } }
Athlete<0> ready!
Athlete<2> ready!
main Thread sleep ...
Athlete<1> ready!
Athlete<0> wait...
Athlete<1> wait...
Athlete<2> wait...
main Thread wake up
Game Ready......
Game start
Athlete<2> have played!
------------------------------------------
进入此函数后,占有锁,但是wait会将锁释放,别的线程就可以进来了。
public synchronized void play(Player player) {}

浙公网安备 33010602011771号