Results 1 to 3 of 3
Thread: Thread questions
- 03-17-2009, 04:37 AM #1
Member
- Join Date
- Feb 2009
- Posts
- 47
- Rep Power
- 0
Thread questions
I have these 3 classes --
Java Code:public class Account { private int balance = 0; void deposit(int amount) { balance += amount; } synchronized int getBalance() { return balance; } }Java Code:public class Customer extends Thread{ Account account; Customer(Account account) { this.account = account; } public void run() { try { for(int i = 0;i<100000;i++) { account.deposit(10); } } catch(Exception e) { e.printStackTrace(); } } }Basically, it just makes some customers (as threads) and calls the deposit method a lot. One question I have is that before I put the synchronized modifier in the deposit method, my output was wrong (it is supposed to be 10,000,000 and it came out to some random crazy number). Why does the program not work without the synchronized modifier? Also, in the BankDemo, why do I have to call the join() method to end a thread?Java Code:public class BankDemo { public final static int NUMCUSTOMERS = 10; public static void main(String args[]) { Account account = new Account(); Customer customers[] = new Customer[NUMCUSTOMERS]; for(int i=0;i<NUMCUSTOMERS;i++) { customers[i] = new Customer(account); customers[i].start(); } //Wait for customer threads to complete for(int i = 0;i<NUMCUSTOMERS;i++) { try { customers[i].join(); } catch(InterruptedException e) { e.printStackTrace(); } } System.out.println(account.getBalance()); } }
- 03-17-2009, 05:47 AM #2
Senior Member
- Join Date
- Dec 2008
- Location
- Hong Kong
- Posts
- 473
- Rep Power
- 5
Reason not work without the synchronized modifier(Thread Interference (The Java™ Tutorials > Essential Classes > Concurrency))
j.join() method...
Thread object j is currently executing, causes the current thread to pause execution until t's thread terminates
(Joins (The Java™ Tutorials > Essential Classes > Concurrency))
i have a question
all Customer use the same account?Last edited by mtyoung; 03-17-2009 at 06:02 AM.
- 03-17-2009, 06:48 AM #3
Hi,
Look into this below link to know more about synchronized modifier.
Sun Certified Java Programmer Pre-Exam EssentialsOne Life!!! Y Serious??? :)
Similar Threads
-
Difference between Thread.yield() and Thread.sleep() methods
By Nageswara Rao Mothukuri in forum New To JavaReplies: 12Last Post: 07-30-2010, 05:37 PM -
passing a value from parent thread to child thread
By sachinj13 in forum Threads and SynchronizationReplies: 7Last Post: 09-07-2008, 09:06 PM -
data from the main/GUI thread to another runnin thread...
By cornercuttin in forum Threads and SynchronizationReplies: 2Last Post: 04-23-2008, 10:30 PM -
If JNI thread call the java object in another thread, it will crash.
By skaterxu in forum Advanced JavaReplies: 0Last Post: 01-28-2008, 07:02 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks