public class MyThread extends Thread {
StringBuffer letter;
public MyThread(StringBuffer s){
this.letter = s;
}
public void run(){
synchronized (letter) {
for(int i=0; i<1000; i++){
System.out.println(Thread.currentThread().getName() + ": " + letter + " index: " + i);
}
char c = letter.charAt(0);
++c;
letter.setCharAt(0, c);
}
}
public static void main(String[] args) {
StringBuffer l = new StringBuffer("a");
MyThread t1 = new MyThread(l);
MyThread t2 = new MyThread(l);
MyThread t3 = new MyThread(l);
t1.setName("Thread1");
t2.setName("Thread2");
t3.setName("Thread3");
t1.start();
t2.start();
t3.start();
}
}
public void run(){
synchronized (letter) {
for(int i=0; i<1000; i++){
System.out.println(Thread.currentThread().getName() + ": " + letter + " index: " + i);
}
char c = letter.charAt(0);
++c;
letter.setCharAt(0, c);
}
}
public void run(){
synchronized (this) {
for(int i=0; i<1000; i++){
System.out.println(Thread.currentThread().getName() + ": " + letter + " index: " + i);
}
char c = letter.charAt(0);
++c;
letter.setCharAt(0, c);
}
}
Obrigado!