用两个线程,一个线程每次对变量i增加1,另一个线程每次对变量i减少1。要求两个线程同步,访问顺序不作要求。我这个怎么不出来
  请高手指点指点  小弟谢谢了
public class ThreadTest
{
public static void main(String args[])
{
publicTest pt = new publicTest();
for(int j=0;j<10;j++)
{
new Thread(new A(pt) ).start();
new Thread(new B(pt) ).start();
}
}
}class A implements Runnable
{
private publicTest pt;
public A(publicTest pt)
{
this.pt = pt;
}
public void run()
{


pt.zijian();

}
}class B implements Runnable
{
private publicTest pt;
public B(publicTest pt)
{
this.pt = pt;
}
public void run()
{
 

  pt.zijia();
 
}
}class publicTest
{
int i=0;
int  zijia()
{
i++;
System.out.print(i);
System.out.println("AAAAAAAAA");
return i;
}
int zijian()
{
i--;
System.out.print(i);
System.out.println("bbbbbbbbb");
return i;
}
}

解决方案 »

  1.   

    for(int j=0;j <10;j++)
    {
    new Thread(new A(pt) ).start();
    new Thread(new B(pt) ).start();
    }你这么一个循环。。不止2个线程了把。最关键的是你的类public class ThreadTest 中pt字段需要同步或者说互斥性访问,你没有做。
      

  2.   

    d8111讲的有道理,你产生了20个线程了,改成只产生两个线程,再试试用下面的形式定义zijia和zijian
    synchronized int  zijia()
    {
    i++;
    System.out.print(i);
    System.out.println("AAAAAAAAA");
    return i;
    }
    synchronized int  zijian() 
    {
    ...
    }