Thread和String需要注意的兩個點

一.Thread

    先來說Thread,Thread類是用來開啓線程的類,自身的run()包含的是方法執行體,start()是方法執行的入口

這是Thread類中run()的源碼:

@Override
public void run(){
    if (target != null){
        target.run();
    }
}

    自己創建線程有兩種方式,一種是自己創建線程類繼承Thread類,一種是通過實現Runnable接口來創建線程,兩種都要重寫run()。

下面舉一個例子:

public class demo_Thread {
    public static void main(String[] args) {
        new Thread(new MyRunnable()).start();
    }
}
class MyThread extends Thread{
    public MyThread(MyRunnable myRunnable) {
        super(myRunnable);
    }

    @Override
    public void run() {
        System.out.println("My Thread.");
    }
}

class MyRunnable implements Runnable{
    @Override
    public void run() {
        System.out.println("My Runnable.");
    }
}

程序執行的結果爲:My Runnable.

public class demo_Thread {
    public static void main(String[] args) {
        new MyThread(new MyRunnable()).start();
    }
}
class MyThread extends Thread{
    public MyThread(MyRunnable myRunnable) {
        super(myRunnable);
    }

    @Override
    public void run() {
        System.out.println("My Thread.");
    }
}

class MyRunnable implements Runnable{
    @Override
    public void run() {
        System.out.println("My Runnable.");
    }
}

程序執行的結果爲My Thread.

 

二.String

     String有一個字符串常量池,但是這個常量池裏的量只在引用賦值的時候使用,而String做“+”拼接時,會調用StringBuilder,new一個StringBuilder對象,再將拼接符兩邊的字符串用append()拼接,生成的StringBuilder再調用toString()方法返回String類型變量,與在常量池中的字符串不是同一個對象(就算字符串的值相同),注意:==比的是真實地地址值,equals比的是具體數值。

這是Object類equals源碼:

public boolean equals(Object obj) {
    return (this == obj);
}

 

這是String類equals源碼:

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                    return false;
                i++;
            }
            return true;
        }
    }
    return false;
}

 

下面舉個例子:

public class test_String {
    public static void main(String[] args) {
        String a = "ab";
        String b = "c";
        String c = a + b;
        String e = a + b;
        String d = "abc";
        String f = "ab" + "";
        System.out.println(c.equals(d));
        System.out.println(c==d);
        System.out.println(e==c);
        System.out.println(a==f);
    }
}

程序運行結果:

true
false
false
true

   

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章