import java.io.IOException; import java.io.InputStream; class Well { private String name; private int water; private Object waterLock = new Object(); public Well(String name, int initial) { this.name = name; this.water = initial; } public void draw(int waterL) { water = water - waterL; } public void pour(int waterL) { synchronized(waterLock) { water = water + waterL; } } public int getWater() { return water; } } class Person { private String name; private int water = 10; private Well well; public Person(String name, Well well) { this.name = name; this.well = well; } public void drawFromWell(int waterL) { well.draw(waterL); water = water + waterL; } public void pourIntoWell(int waterL) { well.pour(waterL); water = water - waterL; } } class ActionThread extends Thread { Person person; public ActionThread(Person person) { this.person = person; } public void run() { for (int j = 0 ; j < 100; j++) { for (int i = 0; i < 1000000; i++) { person.pourIntoWell(1); } } } } class ActionThread2 extends Thread { Person person; public ActionThread2(Person person) { this.person = person; } public void run() { for (int j = 0 ; j < 100; j++) { for (int i = 0; i < 1000000; i++) { person.pourIntoWell(1); } } } } public class Main { public static void main(String[] args) { Well well = new Well("There is a well", 100); Well well2 = new Well("There is another well", 100); Person p1 = new Person("Person A", well); Person p2 = new Person("Person B", well2); ActionThread a = new ActionThread(p1); ActionThread2 b = new ActionThread2(p2); long start = System.currentTimeMillis(); b.start(); a.start(); try { a.join(); b.join(); } catch (InterruptedException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); System.out.println("elasped : " + (end- start)); System.out.println(well.getWater()); } }
2016년 4월 15일 금요일
Thread java
피드 구독하기:
댓글 (Atom)
댓글 없음:
댓글 쓰기