public class ThreadTest2 implements Runnable{
public void run(){
System.out.println("My thread2 is running...");
}
public static void main(String[] args) {
//把Runnable接口的实现类作为参数,构造Thread对象。
Thread t=new Thread(new ThreadTest2());
t.start();
try{
Thread.sleep(3000); //sleep()为Thread类的静态方法
}catch(InterruptedException e){
e.printStackTrace();
}
//返回当前线程的字符串表示形式
String str=Thread.currentThread().toString();
System.out.println(str);
System.out.println("Main thread is running...");
}
}-------------------------------------------------------
上边一段代码中,sleep()方法必须用Thread调用,这我能理解,
但是为什么其他类里只用sleep()不报错,这里只用sleep()就报错呢?
原因在哪里呢?
public void run(){
System.out.println("My thread2 is running...");
}
因为你这是实现Runnable接口,而这个接口里只有run()这一个方法,(不信的话,可以去JAVA API里去查就可以了),所以它这里是不能直接用sleep()的;
class MyThread extends Thread{
int i=0;
public void run(){
while(true){
System.out.println("==="+i++);
try{
sleep(1000);
}catch(InterruptedException e){
return;
}
}
}
}
而这个方法是直接继承的Thread类,因为Thread类里有sleep(),所以可以直接sleep();
众所周知Thread类是属于lang包的,而lang包是不用导入就有的,所以在此情况下就可以直接用Thread.sleep(); 而不能用sleep(),因为这里没有继承Thread类,如下例:
public class Test5 {
public static void main(String[] args) {
String s1 = new String("aaa"),s2 = new String("bbb");
try {
Thread.sleep(4000);
} catch (InterruptedException e)
e.printStackTrace();
}
System.out.println(s1.toString());
System.out.println(s2.toString());
}
}
睡眠4秒后,就会输出结果了
应该是 Thread.sleep()
我的意思是在继承Thread类中可以直接使用sleep()方法,
不过你说到其他的类中必须使用Thread.sleep()也对。我只是想了解为什么是这样,既然已经了解了,
个人感觉以后不管在哪里还是用Thread.sleep()比较好,静态方法。给你提点建议,敬请斟酌:
String s1 = new String("aaa"),s2 = new String("bbb");
好像这样写的很少,应该简洁些:
String s1="aaa";
String s2="bbb";还有System.out.println(s1.toString());
可以直接写:
System.out.println(s1);
因为toString()中参数如果是字符串,还是返回本身,有点多余我学习Java时间也不是很长,共同探讨。哈哈