
关于java多线程的问题 !
为什么最后运行的结果是负数而不是正数呢?但是如果把click++改成click--就会输出正数,好奇怪啊!这是为什么呢?packageTEXT;publicclassHi...
为什么最后运行的结果是负数而不是正数呢?
但是如果把click++改成click-- 就会输出正数,好奇怪啊!
这是为什么呢?
package TEXT;
public class HiLoPri
{
public static void main(String[] args)
{
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker hi =new clicker(Thread.NORM_PRIORITY +2);
clicker lo =new clicker(Thread.NORM_PRIORITY-2);
lo.start();
hi.start();
try
{
Thread.sleep(10000);
}catch(InterruptedException e)
{
System.out.println("main thread exit");
}
lo.stop();
hi.stop();
try
{
hi.t.join();
lo.t.join();
}catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("Low :"+lo.click);
System.out.println("high :"+hi.click);
}
}
class clicker implements Runnable
{
Thread t;
int click=0;
private volatile boolean running =true;
public clicker(int p)
{
t=new Thread(this);
t.setPriority(p);
}
public void run()
{
while (running)
{
click++;
}
}
public void start()
{
t.start();
}
public void stop()
{
running=false;
}
} 展开
但是如果把click++改成click-- 就会输出正数,好奇怪啊!
这是为什么呢?
package TEXT;
public class HiLoPri
{
public static void main(String[] args)
{
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker hi =new clicker(Thread.NORM_PRIORITY +2);
clicker lo =new clicker(Thread.NORM_PRIORITY-2);
lo.start();
hi.start();
try
{
Thread.sleep(10000);
}catch(InterruptedException e)
{
System.out.println("main thread exit");
}
lo.stop();
hi.stop();
try
{
hi.t.join();
lo.t.join();
}catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("Low :"+lo.click);
System.out.println("high :"+hi.click);
}
}
class clicker implements Runnable
{
Thread t;
int click=0;
private volatile boolean running =true;
public clicker(int p)
{
t=new Thread(this);
t.setPriority(p);
}
public void run()
{
while (running)
{
click++;
}
}
public void start()
{
t.start();
}
public void stop()
{
running=false;
}
} 展开
1个回答
展开全部
这个问题是因为你定义的click为int型,click++可能超过了int的有效长度
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询