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遍,该怎么实现呢????????
{
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遍,该怎么实现呢????????
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++;
}
}
}
};
应该在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();
}
}
{
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++;
}
}
}
};
控制下就好了