public class Demo extends Thread
{
public static Integer i=100;//初始值100
private String sign;
//构造方法
public Demo(String str)
{
this.sign = str;
}
//线程运行的方法
@SuppressWarnings("static-access")
public void run()
{
if ("+".equals(this.sign))
{
for (int j = 0; j < 2000; j++)
{
this.i += 2;
}
}
else if ("-".equals(this.sign))
{
for (int j = 0; j < 2000; j++)
{
this.i -= 2;
}
}
else if ("*".equals(this.sign))
{
for (int j = 0; j < 2000; j++)
{
this.i *= 2;
}
}
else if ("/".equals(this.sign))
{
for (int j = 0; j < 2000; j++)
{
if (this.i != 0)
{
this.i /= 2;
}
}
}
}
@SuppressWarnings("static-access")
public static void main(String arg[]) throws Exception
{
new Thread(new Demo("+")).start();//启动+
new Thread(new Demo("-")).start();//启动-
new Thread(new Demo("*")).start();//启动x
new Thread(new Demo("/")).start();//启动/
Thread.currentThread().sleep(1000);//当前线程暂停1000秒,让其他4个线程 运行完
System.out.println(Demo.i);//输出结果
}
}
如果 int变量 是静态的,最后为0;