public class ThreadTest
{
public static void main(String [] args){
int i = 100;
ThreadAdd add = new ThreadAdd(i);
ThreadCut cut = new ThreadCut(i);
Thread t1 = new Thread(add);
Thread t2 = new Thread(add);
Thread t3 = new Thread(cut);
Thread t4 = new Thread(cut);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class ThreadAdd implements Runnable
{
private int i;
public ThreadAdd(int i){
this.i = i;
}
Object obj = new Object();
public void run(){
for(int j = 0;j<50;j++){
synchronized(obj){
i++;
}
System.out.println(i);
}
}
}
class ThreadCut implements Runnable
{
private int i;
public ThreadCut(int i){
this.i = i;
}
Object obj = new Object();
public void run(){
for(int j = 0;j<50;j++){
synchronized(obj) {
i--;
}
System.out.println(i);
}
}
}
|