日期:2014-05-20  浏览次数:20729 次

不能编译3
class apple1 implements Runnable
{
public void run()
{
for(int a=0;a<10;a++)
{
System.out.println("线程"+Thread.currentThread().getName()+"---------"+"ABCABC.....");
}
}
};
public class apple
{
public static void main(String[] args) 
{
apple1 aa=new apple1();
Thread A=new Thread(aa,"A");
Thread B=new Thread(aa,"B");
Thread C=new Thread(aa,"C");
A.start();
B.start();
C.start();
}
};
上面每个线程都运行了10遍,
我想让它们加起来一共运行10遍,该怎么实现呢????????

------解决方案--------------------
修改你的Runnable类
Java code
class apple1 implements Runnable
{
    int index = 0; //使用共同资源
    public void run()
    {
        //for(int a=0;a<10;a++)
        while(true)
        {
            synchronized(this) { //使用同步
                if (index >= 10) break;
                System.out.println("线程"+Thread.currentThread().getName()+"---------"+"ABCABC.....");
               index++;
            }
        }
    }
};

------解决方案--------------------
楼上的可以实现,楼主你只要将for中的变量a定义成全局变量也能实现,但是要记得像楼上的那样加个同步,不然跑出来的效果有可能会大于10个
------解决方案--------------------
探讨
修改你的Runnable类

Java code
class apple1 implements Runnable
{
int index = 0; //使用共同资源
public void run()
{
//for(int a=0;a<10;a++)
while(true)
{
……

------解决方案--------------------
class apple1 implements Runnable
{
int T = 0; //使用共同资源
public void run()
{
//for(int a=0;a<10;a++)
while(true)
{
synchronized(this) { //使用同步
if (T >= 10) break;
System.out.println("线程"+Thread.currentThread().getName()+"---------"+"ABCABC.....");
T++;
}
}
}
};
控制下就好了