那是因为你随机数产生的是负数,你说让一个线程休眠时间为负数,那怎么可能,正确如下:class MyThread extends Thread{
public void run(){
char ch;
try{
for (ch='A';ch<='Z';ch++){
System.out.print(ch+" ");
Thread.sleep((int)(500+(2000-500)*Math.random()));
}
}catch (InterruptedException e){
return;
}
}
}
class MyRunnable implements Runnable {
public void run(){
char ch;
try{
for (ch='a';ch<='z';ch++){
System.out.print(ch+" ");
Thread.sleep((int)(500+(2000-500)*Math.random()));
}
}catch (InterruptedException e){
return;
}
}
}
public class ThreadTest {
public static void main(String args[]) {
MyThread t1 = new MyThread();
MyRunnable r = new MyRunnable();
Thread t2 = new Thread(r);
t1.run();
t2.start();
}
}
如果是t1.start()那么将会交替产生大小字母,而t1.run()则会产生出所有大写字母后,再差生所有小写字母
楼上说的对啊,不过该这样改,把500+(2000-5000)*Math.random() 改成500+15000*Math.random()
class MyThread extends Thread{
public void run(){
char ch;
try{
for (ch='A';ch<='Z';ch++){
System.out.print(ch+" ");
sleep((int)(500+15000*Math.random()));
}
}catch (InterruptedException e){
return;
}
}
}
class MyRunnable implements Runnable {
public void run(){
char ch;
try{
for (ch='a';ch<='z';ch++){
System.out.print(ch+" ");
Thread.sleep((int)(500+15000*Math.random()));
}
}catch (InterruptedException e){
return;
}
}
}
public class ThreadTest {
public static void main(String args[]) {
MyThread t1 = new MyThread();
MyRunnable r = new MyRunnable();
Thread t2 = new Thread(r);
t1.start();
t2.start();
}
}