这段代码为什么不能多个线程同时进行 class TextThread extends Thread {
public static void main(String args[])
{
TextThread2 tt = new TextThread2();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
}
}
class TextThread2 implements Runnable {
int ticker=100;
String str = "";
public void run()
{
while(true)
{
if(ticker>0)
{
Thread thread = Thread.currentThread();
System.out.println("Thread()"+thread.getName()+" "+ticker--);
}
}
}
}
public static void main(String args[])
{
TextThread2 tt = new TextThread2();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
}
}
class TextThread2 implements Runnable {
int ticker=100;
String str = "";
public void run()
{
while(true)
{
if(ticker>0)
{
Thread thread = Thread.currentThread();
System.out.println("Thread()"+thread.getName()+" "+ticker--);
}
}
}
}
你要么让主线程等一等再退出,要么在线程启动前重设一下它的daemon属性。
if(ticker>0)
{
Thread thread = Thread.currentThread();
System.out.println("Thread()"+thread.getName()+" "+ticker--);
}
加上
if(ticker>0)
{
Thread thread = Thread.currentThread();
System.out.println("Thread()"+thread.getName()+" "+ticker--);
try {
Thread.sleep(3000)
} catch(InterruptedException e) {
e.printStackTrace();
}
}这样以保证后面的线程和前面的线程交叉执行实现同步,另外建议每起一个线程都给它起个名字Thread t1=new thread(tt);
t1.setName(t1);
...这样结果比较好看清楚