Thursday, February 6, 2014

Java - synchronized

1. example 1

class Contribution {
private int amount; // check example 2

public synchronized void donate() { // check example 2
amount++;
}

public int getTotal() {
return amount;
}
}

class Contributor extends Thread {
private Contribution contribution;
private String name;

public Contributor(Contribution contribution, String name) {
this.contribution = contribution;
this.name = name;
}

public void run() {
for (int i = 0; i < 1000; i++) {
contribution.donate();
}

System.out.format("%s total = %d\n", name, contribution.getTotal());
}
}

public class Test {

public static void main(String[] args) {
final int CONTRIBUTOR_NO = 10;

Contributor[] contributors = new Contributor[CONTRIBUTOR_NO];
Contribution contribution = new Contribution(); // check example 2

for (int i = 0; i < CONTRIBUTOR_NO; i++) {
contributors[i] = new Contributor(contribution, String.valueOf(i));
contributors[i].start();
}
}
}

2. example 2

class Contribution {
private static int amount; // check example 1

public static synchronized void donate() { // check example 1
amount++;
}

public int getTotal() {
return amount;
}
}

class Contributor extends Thread {
private Contribution contribution;
private String name;

public Contributor(Contribution contribution, String name) {
this.contribution = contribution;
this.name = name;
}

public void run() {
for (int i = 0; i < 1000; i++) {
contribution.donate();
}

System.out.format("%s total = %d\n", name, contribution.getTotal());
}
}

public class Test {

public static void main(String[] args) {
final int CONTRIBUTOR_NO = 10;

Contributor[] contributors = new Contributor[CONTRIBUTOR_NO];

for (int i = 0; i < CONTRIBUTOR_NO; i++) {
Contribution contribution = new Contribution(); // check example 1
contributors[i] = new Contributor(contribution, String.valueOf(i));
contributors[i].start();
}
}
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.