import java awt geom public class Ball private
Программный код // Класс кружок import java. awt. geom. *; public class Ball { private static final int XSIZE = 15; private static final int YSIZE = 15; private double x = 0; private double y = 0; private double dx = 1; private double dy = 1; public void move(Rectangle 2 D bounds) { x += dx; y += dy; if (x < bounds. get. Min. X()) { x = bounds. get. Min. X(); dx = -dx; } ……. . // проверки на достижение границ } // Панель для хранения и отображения //экземпляров класса Ball import java. awt. *; import java. util. *; import javax. swing. *; public class Ball. Component extends JPanel{ Array. List<Ball> balls = new Array. List<Ball>(); public void add(Ball b) { balls. add(b); } public Ellipse 2 D get. Shape() {return new Ellipse 2 D. Double(x, y, XSIZE, YSIZE); } } } public void paint. Component(Graphics g) { super. paint. Component(g); // очистка экрана Graphics 2 D g 2 = (Graphics 2 D) g; for (Ball b : balls) {g 2. fill(b. get. Shape()); } }
Программный код // Класс фрейм, на котором все размещается class Bounce. Frame extends JFrame{ private Ball. Component comp; public static final int STEPS = 1000; public static final int DELAY = 3; public void add. Button(Container c, String title, Action. Listener listener) { JButton button = new JButton(title); c. add(button); button. add. Action. Listener(listener); } public Bounce. Frame() { set. Size(450, 350); set. Title("Bounce"); comp = new Ball. Component(); add(comp, Border. Layout. CENTER); JPanel button. Panel = new JPanel(); add. Button(button. Panel, "Start", new Action. Listener() {public void action. Performed(Action. Event event) {add. Ball(); } }); public void add. Ball(){ try{ Ball ball = new Ball(); comp. add(ball); for (int i = 1; i <= STEPS; i++) { ball. move(comp. get. Bounds()); comp. paint(comp. get. Graphics()); Thread. sleep(DELAY); } }catch (Interrupted. Exception e){; } }} add. Button(button. Panel, "Close", new Action. Listener() { public void action. Performed(Action. Event event) {System. exit(0); } }); add(button. Panel, Border. Layout. SOUTH); } public class Bounce{ public static void main(String[] args) { Event. Queue. invoke. Later(new Runnable(){ public void run(){ JFrame frame = new Bounce. Frame(); frame. set. Default. Close. Operation(JFrame. EXIT_ frame. set. Visible(true); }}); } }
Модификация программного кода // Новый класс, реализующий интерфейс class Ball. Runnable implements Runnable { private Ball ball; private Component component; public static final int STEPS = 1000; public static final int DELAY = 5; public Ball. Runnable(Ball a. Ball, Component a. C) { ball = a. Ball; component = a. C; } public void run() { try { for (int i = 1; i <= STEPS; i++){ ball. move(component. get. Bounds()); component. repaint(); Thread. sleep(DELAY); } } catch (Interrupted. Exception e){} } } //метод add. Ball до «многопоточности» public void add. Ball(){ try{ Ball ball = new Ball(); comp. add(ball); for (int i = 1; i <= STEPS; i++) { ball. move(comp. get. Bounds()); comp. paint(comp. get. Graphics()); Thread. sleep(DELAY); } }catch (Interrupted. Exception e){; } } //метод add. Ball после введения // «многопоточности» public void add. Ball(){ Ball ball = new Ball(); comp. add(ball); Runnable r = new Ball. Runnable(b, comp); Thread t = new Thread(r); t. start(); }
Код примера public class Unsynch. Bank. Test{ public static final int NACC = 100; public static final double INIT_BAL = 1000; public static void main(String[] args){ Bank b = new Bank(NACC, INIT_BAL); int i; for (i = 0; i < NACC; i++){ Transfer. Runnable r = new Transfer. Runnable(b, i, INIT_BAL); Thread t = new Thread(r); t. start(); } } } public class Bank{ private final double[] accounts; public Bank(int n, double initial. Balance){ accounts = new double[n]; for (int i = 0; i < accounts. length; i++) accounts[i] = initial. Balance; } public void transfer(int from, int to, double amount){ if (accounts[from] < amount) return; System. out. print(Thread. current. Thread()); accounts[from] -= amount; System. out. printf(" %10. 2 f from %d to %d", mount, from, to); accounts[to] += amount; System. out. printf(" Total Balance: %10. 2 f%n", get. Total. Balance()); } public double get. Total. Balance() { double sum = 0; for (double a : accounts) sum += a; return sum; } public int size(){ return accounts. length; }}
Продолжение кода примера public class Transfer. Runnable implements Runnable{ private Bank bank; private int from. Account; private double max. Amount; private int DELAY = 10; public Transfer. Runnable(Bank b, int from, double max){ bank = b; from. Account = from; max. Amount = max; } public void run(){ try{ while (true){ int to. Account = (int) (bank. size() * Math. random()); double amount = max. Amount * Math. random(); bank. transfer(from. Account, to. Account, amount); Thread. sleep((int) (DELAY * Math. random())); } } catch (Interrupted. Exception e){ } } }
Пример public void transfer(int from, int to, double amount){ bank. Lock. lock(); try{ System. out. print(Thread. current. Thread()); accounts[from] -= amount; System. out. printf(" %10. 2 f from %d to %d", amount, from, to); accounts[to] += amount; System. out. printf(" Total Balance: %10. 2 f%n", get. Total. Balance()); } finally{ bank. Lock. unlock(); }} …. private Lock bank. Lock=new Reentrant. Lock();
- Slides: 27