当前位置: 技术问答>java相关
程序中有3个线程,怎么只有一个工作?
来源: 互联网 发布时间:2015-08-07
本文导语: 程序如下 public class TryThread extends Thread { private String name; private int age; public TryThread(String n, int a) { this.name = n; this.age = a; } public void run() { while(true) { try { System.out.println(name + " " +...
程序如下
public class TryThread extends Thread
{
private String name;
private int age;
public TryThread(String n, int a)
{
this.name = n;
this.age = a;
}
public void run()
{
while(true)
{
try
{
System.out.println(name + " " + age);
Thread.sleep(200);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
public static void main(String[] args)
{
Thread t1 = new TryThread("wang", 20);
Thread t2 = new TryThread("li", 21);
Thread t3 = new TryThread("zhao", 19);
t1.run();
t2.run();
t3.run();
}
}
输出结果为
wang 20
wang 20
......
为什么t2,t3不工作?谢谢?
public class TryThread extends Thread
{
private String name;
private int age;
public TryThread(String n, int a)
{
this.name = n;
this.age = a;
}
public void run()
{
while(true)
{
try
{
System.out.println(name + " " + age);
Thread.sleep(200);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
public static void main(String[] args)
{
Thread t1 = new TryThread("wang", 20);
Thread t2 = new TryThread("li", 21);
Thread t3 = new TryThread("zhao", 19);
t1.run();
t2.run();
t3.run();
}
}
输出结果为
wang 20
wang 20
......
为什么t2,t3不工作?谢谢?
|
while(true)
{
try
{
...
sleep(200); //因为TryThread是Thread的子类,“Thread.”可以省略
}
catch(InterruptedException e)
{
...
}
}
在public static void main(String[] args)中,启动线程使用t1.start();
t2.start();
t3.start();
是正规用法
{
try
{
...
sleep(200); //因为TryThread是Thread的子类,“Thread.”可以省略
}
catch(InterruptedException e)
{
...
}
}
在public static void main(String[] args)中,启动线程使用t1.start();
t2.start();
t3.start();
是正规用法
|
楼上的说得不错,启动线程用*.start()
如果想要线程能自动终止,最好加上生存时间控制。
public class TryThread extends Thread
{
private String name;
private int age;
private int life;
.......
.......
.......
public TryThread(String n, int a,int l)
{
this.name = n;
this.age = a;
life = l;
}
public void run()
{
int i = 0;
while( i
如果想要线程能自动终止,最好加上生存时间控制。
public class TryThread extends Thread
{
private String name;
private int age;
private int life;
.......
.......
.......
public TryThread(String n, int a,int l)
{
this.name = n;
this.age = a;
life = l;
}
public void run()
{
int i = 0;
while( i