public class Test
{
private int num;
public static void main(String[] args)
{
Test t = new Test();
Add add = t.new Add();
Sub sub = t.new Sub();
Thread t1 = new Thread(add);
Thread t2 = new Thread(sub);
t1.start();
t2.start();
}
private synchronized void add()
{
System.out.println(Thread.currentThread().getName()+":"+num++);
}
private synchronized void sub()
{
System.out.println(Thread.currentThread().getName()+":"+num--);
}
class Add implements Runnable
{
public void run()
{
for(int i=0;i<200;i++)
{
add();
}
}
}
class Sub implements Runnable
{
public void run()
{
for(int i=0;i<200;i++)
{
sub();
}
}
}
} |