public class dddd extends Thread
{
static int i=100;
public synchronized void run()
{
System.out.println(Thread.currentThread().getName()+" "+i);
i--;
}
public static void main(String[] args)
{
int i=100;
dddd h=new dddd();
Thread a=new Thread(h);
Thread b=new Thread(h);
Thread c=new Thread(h);
Thread d=new Thread(h);
Thread e=new Thread(h);
while(dddd.i)
{
a.start();
b.start();
c.start();
d.start();
e.start();
}
}
}
我想建立5个线程 然后有一个计数器 当计数器的数i<1时停止进程
为什么while循环内只执行一次后就开始报错
------解决方案--------------------
问题解决了一大半,利用的是外层循环,内层一个判断
代码如下:
package test;
class Window implements Runnable {
public void run() {
for(int k = 0;k<99;k++){
synchronized(this)
{
try{
Thread.sleep(100);
}catch(Exception e){}
if(i>=1)
System.out.println(Thread.currentThread().getName() + " "
+ i--);
}
}
}
private int i = 100;
}
public class Main {
public static void main(String[] args) {
Window h = new Window();
Thread a = new Thread(h, "a");
Thread b = new Thread(h, "b");
Thread c = new Thread(h, "c");
Thread d = new Thread(h, "d");
Thread e = new Thread(h, "e");
Thread f = new Thread(h, "f");
Thread g = new Thread(h, "g");
a.start();
b.start();
c.start();
d.start();
e.start();
f.start();
g.start();
}
}
原理我也说不太懂,外层循环至少要保证和i的个数一样才比较科学……
------解决方案--------------------
原理我也说不太懂,外层循环至少要保证和i的个数一样才比较科学……
这几天多线程的问题不少,不能语言交流确实不太好教明白别人怎么写多线程,尴尬。
不要在run()里面写synchronized(this),没什么用。