62,614
社区成员
发帖
与我相关
我的任务
分享
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();
}
}
}
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();
}