您的位置:首页 > 编程语言 > Java开发

读"Think in Java"后笔记(1)

2005-10-13 18:21 525 查看
有在它初使化时才分配空间。String[] arrNames=new String[5]; 这条语句也并没有对arrNames[0],arrNames[1] 等实例化,只对是arrNames实例化了
public class MyObject {
MyObject(){
System.out.println("MyObject is created!");
}

public static void main(String[] args){
MyObject[] myObjects =new MyObject[5]; // nothing printed in thing line.
System.out.println("By now, nothing has been printed. myObjects have not been created!");
myObjects[0]=new MyObject(); //involve MyObject's Constructor.
}
}
 
2. 线程
2.1 一个简单的Thread只需要继承Thread类,将自己的运行的内容写入run方法中。然后在需要启动的地方调用myClass.start()方法就可以了。
public class TestThread extends Thread {
private int count=5;
private static int threadCount=0;
public String toString(){
   return super.getName()+" " + (count--);
}
public TestThread(){
   super("#Thread" + (++threadCount));
start();
}
public void run(){
   while(true){
    System.out.println(this);
     if (count==0) return;
   }
}
}
 
2.2 deamon的含义是后台运行程序。它也是Thread类的一个属性。当通过MyThread.setDeamon(True)设置一个Thread为Deamon后,这个线程将在调用都后台运行,当调用者终止后它也一起自动终止。
2.3 当一个类需要继承另外的类的时候,再直接继承Thread就不可以了,这时可以让这个类实现Runnable接口(就一个run()方法),然后用new Thread(new MyClass())的方法来实际新建线程的目的。
public class RunnableThread implements Runnable {
private int countDown = 5;
public String toString() {
return "#" + Thread.currentThread().getName() +
": " + countDown;
}
public void run() {
while(true) {
System.out.println(this);
if(--countDown == 0) return;
}
}
public static void main(String[] args) {
for(int i = 1; i <= 5; i++)
new Thread(new RunnableThread(), "" + i).start();
// Output is like SimpleThread.java
}
}
 2.4 考虑到每加一种线程单独增加一个类有时显得不简洁,这时使用内部类(innerClass)是一个不错的选择。
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐