本帖最后由 刘永建 于 2013-6-7 12:32 编辑
代码写到这里运行的时候,为什么i和m的输出不是从1开始,而改变mainThread的字符串输出,就会正常,这是为什么呢?
package com.jianjian;
/*子线程循环10次,接着主线程循环100,接着
* 又回到子线程循环10次,接着再回到主线程又循环100,如此循环50次,*/
public class Test7
{
public static void main(String[] args)
{ //保证调用线程的是一个对象
final Sequence sequence = new Sequence();
new Thread(new Runnable()
{
@Override
public void run()
{
for(int m = 1; m <=50; m ++)
{
sequence.subThread(m);
sequence.mainThread(m);
}
}
}).start();
}
}
//写一个类,有两个方法,分别用来执行子线程,和主线程
class Sequence
{
//总循环50次,在线程中执行,但是还是最好要在执行输出的方法中显示出是第几次循环Loop,所以可以传递一个参数进来;
//没有想到不要紧,想到了就要解决好,或者实现规划好,就没必要进行太多的修改
public void subThread(int m)
{
for(int i = 1; i <= 10; i++)
{
System.out.println("sub thread operating: "+i+" loop of "+m);
}
}
public void mainThread(int m )
{
for(int i = 1 ; i <=100; i ++)
System.out.println("main Thread operating " +i+ "loop of "+ m);
}
}
输出的结果却是:main Thread operating 91loop of 30
main Thread operating 92loop of 30
main Thread operating 93loop of 30
main Thread operating 94loop of 30
main Thread operating 95loop of 30
main Thread operating 96loop of 30
main Thread operating 97loop of 30
main Thread operating 98loop of 30
main Thread operating 99loop of 30
main Thread operating 100loop of 30
sub thread operating: 1 loop of 31
sub thread operating: 2 loop of 31
sub thread operating: 3 loop of 31
sub thread operating: 4 loop of 31
sub thread operating: 5 loop of 31
sub thread operating: 6 loop of 31
sub thread operating: 7 loop of 31
sub thread operating: 8 loop of 31
sub thread operating: 9 loop of 31
sub thread operating: 10 loop of 31
main Thread operating 1loop of 31
main Thread operating 2loop of 31
main Thread operating 3loop of 31
main Thread operating 4loop of 31
main Thread operating 5loop of 31
|