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遍,该怎么实现呢????????

解决方案 »

  1.   

    修改你的Runnable类
    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++;
                }
            }
        }
    };
      

  2.   

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

  3.   


    应该在while中加个sleep,否则每次都是一个线程工作,其它得不到锁
    while (true) {
    synchronized (this) { // 使用同步
    if (index >= 10)
    break;
    System.out.println("线程" + Thread.currentThread().getName()
    + "---------" + "ABCABC.....");
    index++;
    }
    try {
    Thread.sleep(100);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
      

  4.   

    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++;
                }
            }
        }
    };
    控制下就好了