java学习之疑――线程
class XThread extends Thread{
long count;
XThread(String name){
super(name);
}
public void run(){
for(int i=1;i<=5;i++){
for(int j=1;j<=10000;j++){
count+=1;
}
try{
Thread.sleep(1000);
}
catch(Exception e){
}
}
}
}
public class Application{
public static void main(String[] args){
XThread highPriorityThreadObj=new XThread(">>>Thread对象");
XThread lowPriorityThreadObj=new XThread("<<<Thread对象");
highPriorityThreadObj.setPriority(Thread.NORM_PRIORITY+1);
lowPriorityThreadObj.setPriority(Thread.NORM_PRIORITY-1);
lowPriorityThreadObj.start();
highPriorityThreadObj.start();
try{
Thread.sleep(1000);
}
catch(Exception e){
}
System.out.println("highPriorityThreadObj的count值是"+highPriorityThreadObj.count);
System.out.println("lowPriorityThreadObj的count值是"+lowPriorityThreadObj.count);
System.out.println("highPriorityThreadObj is alive?"+highPriorityThreadObj.isAlive());
System.out.println("lowPriorityThreadObj is alive?"+lowPriorityThreadObj.isAlive());
}
}
long count;
XThread(String name){
super(name);
}
public void run(){
for(int i=1;i<=5;i++){
for(int j=1;j<=10000;j++){
count+=1;
}
try{
Thread.sleep(1000);
}
catch(Exception e){
}
}
}
}
public class Application{
public static void main(String[] args){
XThread highPriorityThreadObj=new XThread(">>>Thread对象");
XThread lowPriorityThreadObj=new XThread("<<<Thread对象");
highPriorityThreadObj.setPriority(Thread.NORM_PRIORITY+1);
lowPriorityThreadObj.setPriority(Thread.NORM_PRIORITY-1);
lowPriorityThreadObj.start();
highPriorityThreadObj.start();
try{
Thread.sleep(1000);
}
catch(Exception e){
}
System.out.println("highPriorityThreadObj的count值是"+highPriorityThreadObj.count);
System.out.println("lowPriorityThreadObj的count值是"+lowPriorityThreadObj.count);
System.out.println("highPriorityThreadObj is alive?"+highPriorityThreadObj.isAlive());
System.out.println("lowPriorityThreadObj is alive?"+lowPriorityThreadObj.isAlive());
}
}
Z:\>javac Application.java
Z:\>java Application
highPriorityThreadObj的count值是20000
lowPriorityThreadObj的count值是10000
highPriorityThreadObj is alive?true
lowPriorityThreadObj is alive?true
为什么会出现20000和10000啊?我是java小白,希望路过的大牛们能点播一二o(∩_∩)o...
----------------解决方案--------------------------------------------------------
这很正常啊,首先线程的执行就不能非常确定的
你的程序一起动,两个线程就开始要起动了,然后进入第一个循环,加10000然后再睡1000毫秒,可能就在你睡第二个1000毫秒的时候,第二个循环已经执行了
----------------解决方案--------------------------------------------------------