本人初学Java多线程,希望看到明显的资源竞争现象,但是我的代码运行很久都不能看到混乱的数值,而且不知道为什么,电脑小风扇扇的我害怕
class Pair
{
private int x=0,y=0;
void increaseX()//正常情况下,x永远是偶数
{
x++;
x++;
}
void increaseY()
{
y++;
y++;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
}
class UseSharePair
{
public static void main(String [] args)
{
Pair p=new Pair();
ExecutorService exec=Executors.newCachedThreadPool();
exec.execute(new Runnable()
{
public void run()
{
while(true)
{
p.increaseX();
p.increaseY();
System.out.println("编号1:"+"x:"+p.getX()+" y:"+p.getY());
}
}
});
exec.execute(new Runnable()
{
public void run()
{
while(true)
{
p.increaseX();
p.increaseY();
System.out.println("编号2:"+"x:"+p.getX()+" y:"+p.getY());
}
}
});
if(p.getX()%2!=0||p.getY()%2!=0)
{
System.out.println("x=" + p.getX() + " y= " + p.getY());
exec.shutdown();
System.exit(0);
}
}
}