Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
쓰레드 critical section
//'main' method must be in a class 'Rextester'. //Compiler version 1.8.0_72 class Rextester { public static void main(String[] args) { SharedArea area = new SharedArea(); area.account1 = new Account("111-111-111","이몽룡",20000000); area.account2 = new Account("222-222-222","성춘향",10000000); TransferThread thread1 = new TransferThread(area); PrintThread thread2 = new PrintThread(area); thread1.start(); thread2.start(); } } class TransferThread extends Thread { SharedArea sharedArea; TransferThread(SharedArea area) { sharedArea=area; } public void run() { for(int cnt=0;cnt<12;cnt++) { synchronized (sharedArea) { sharedArea.account1.withdraw(1000000); System.out.println("이몽룡 계좌 : 100만원 인출"); sharedArea.account2.deposit(1000000); System.out.println("성춘향 계좌 : 100만원 입금"); } } } } class Account { String AccountNo; String ownerName; int balance; Account(String accountNo, String ownerName, int balance) { this.AccountNo=accountNo; this.ownerName=ownerName; this.balance=balance; } void deposit(int amount) { balance += amount; } int withdraw(int amount) { if(balance < amount) return 0; balance -= amount; return amount; } } class SharedArea { Account account1; Account account2; } class PrintThread extends Thread { SharedArea sharedArea; PrintThread(SharedArea area) { sharedArea = area; } public void run() { for(int cnt=0;cnt<3;cnt++) { synchronized (sharedArea) { int sum=sharedArea.account1.balance + sharedArea.account2.balance; System.out.println("계좌 잔액 합계 : " + sum); } try { Thread.sleep(1); } catch(InterruptedException e) { System.out.println(e.getMessage()); } } } }
run
|
edit
|
history
|
help
0
4th question
jb11.0 threads tick tock
cuboid volume
swastik
pow x^n
jb12.0 threads.enums
laba
jb11.0 threads tick tock 1.0
1 to 100 except 30 to40
jb7.0 extends.override