题目:
子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,接着再回到主线程
循环100次,如此循环50次,请写出程序.
以下这个题目的代码,我有几个地方看不懂,请懂的朋友解释一下,谢谢!
public class MemoryTest
{
public static void main(String[] args)
{
new MemoryTest().init();
}
protected static int LOOPCOUNT = 5;
public void init()
{
final Business bs = new Business();
new Thread()
{
public void run()
{
boolean bMale = false;
for(int n =1;n<=LOOPCOUNT;n++)
{
bs.subMethod(n);
}
}

}.start();

new Thread(new Runnable()
{
public void run()
{
for(int n =1;n<=LOOPCOUNT;n++)
{
bs.mainMethod(n);
}
}

}).start();
}
}
class Business
{
boolean bShouldSub = true;
public synchronized void subMethod(int num)
{
try
{
if(!bShouldSub)  //这个IF语句是什么意思?
{
this.wait();  //这条语句在这里起什么作用?
}
Thread.sleep(100); //为什么这里要加上一条这个语句?
for(int i=0;i<10;i++)
{
System.out.println(
Thread.currentThread().getName() + ": loop of " + i+ ":" + " time of " + num);
}
bShouldSub = false;
this.notify();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}

public synchronized void mainMethod(int num)
{
try
{
if(bShouldSub) //这个IF语句是什么意思?
{
this.wait(); //这条语句在这里起什么作用?
}
Thread.sleep(100);  //为什么这里要加上一条这个语句?
for(int i=0;i<5;i++)
{
System.out.println(
Thread.currentThread().getName() + ": loop of " + i + ":" + " time of " + num);
}
bShouldSub = true;
this.notify();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}

}

解决方案 »

  1.   

     if(!bShouldSub)  //如果不等于 bshouldSub
                {
                    this.wait();  //处于等到状态            }
                Thread.sleep(100); //休眠100毫秒  给别的线程执行的机会  
      

  2.   

    if(!bShouldSub)    ---判断该执行哪个线程this.wait();        ----让当前执行线程上的对象处于等待状态。
    Thread.sleep(100);  ----当前线程睡眠100毫秒(此语句为保险起见,可有可无)
      

  3.   

    初始 bShouldSub = true,执行subMethod的相关线程,mainMethod相关线程处于wait状态,subMethod循环完后,置bShouldSub =false通过notify唤起mainMethod线程即执行mainMethod,mainMethod执行完后再置bShouldSub=true
    使其线程处于wait状态,通过notify唤起subMethod的相关线程
      

  4.   

    线程是有优先级的,你可以设置啊。如果没有设置优先级,那么肯定是看cpu了,它心情好,愿意运行那个就运行哪个。
      

  5.   

    其实这种,完全可以不用多线程来实现。
    Runnable mainTask = new Runnable() {
    public void run() {
    // do sth
    }
    };
    Runnable subTask = new Runnable() {
    public void run() {
    // do sth another
    }
    };for (int i = 0; i < 50; i++) {
    for (int j = 0; j < 10; j++)
    subTask.run();
    for (int j = 0; j < 100; j++)
    mainTask.run();
    }ps:多线程是用来并发的,不是用来线性执行的。如果你的需求是固定的线性执行,那么还是不要用线程好了