class Tisk2 implements Runnable
{
int tisk = 10000;
public void run() //最开始的代码,你将synchronized加到run()方法上,由于里面有个判断while(Tisk>0),所以一直执行的是同一个线程,while不判断完不罢休,呵呵 {
while (true)
{
synchronized(Tisk2.class) //出现负数的情况是由于线程与线程之间的执行次序,有些线程还没执行完,其实其他线程已经执行了一部分,
//所以需要加上synchronized代码块!并才用双重判断,类似与单例设计模式一样!
{
if (tisk>0)
{
System.out.println(Thread.currentThread().getName()+"....."+tisk--);
}
else
break;
}
}
}
public static void main(String[] args)
{
Tisk2 t= new Tisk2();
Thread th1 = new Thread(t,"th1");
Thread th2 = new Thread(t,"th2");
Thread th3= new Thread(t,"th3");
Thread th4 = new Thread(t,"th4");
Thread th5 = new Thread(t,"th5");
Thread th6 = new Thread(t,"th6");
th1.start();
th2.start();
th3.start();
th4.start();
th5.start();
th6.start();
}
} |