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

博客介绍了Java中数组实例化的情况,如String数组声明时仅对数组本身实例化,元素未实例化。还阐述了线程相关知识,包括继承Thread类创建线程、设置Deamon属性、实现Runnable接口创建线程以及使用内部类创建线程等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有在它初使化时才分配空间。

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)是一个不错的选择。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值