public class TestSyncTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestSync job = new TestSync();
Thread a = new Thread(job);
Thread b = new Thread(job);
a.setName("first");
b.setName("second");
a.start();
b.start();
}
}
class TestSync implements Runnable{
private int balance;
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<50;i++){
increment();
System.out.println(Thread.currentThread().getName()+" Balance is "+balance);
}
}
public void increment(){
synchronized(this){
int i = balance;
balance = i+1;
}
}
}
No comments:
Post a Comment