天天看點

多線程進一步的了解------------線程的建立

public class TestThread1 {
    public static void main(String[] args) {
        Thread thread = new Thread(){
            @Override
            public void run () {
                while (true) {
                    try {
                        Thread.sleep(500);//讓它休息0.5秒
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "----------------");
                }
            }
        };
        thread.start();
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "----------------");
                }
            }
        });
        thread1.start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("4"+Thread.currentThread().getName() + "----------------");
                }
            }
        }){
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("3"+Thread.currentThread().getName() + "----------------");
                }
            }
        }.start();
    }
}      

雖然建立多線程的方式有兩種但是我們一般常用

Thread thread1 = new Thread(new Runnable() {
    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "----------------");
        }
    }
});
thread1.start();

因為這種方式更能展現面向對象的方式,把線程的建立和代碼部分分開了,還有一點必須要糾正的是,并不是說多線程一定會使項目快很多,還是那句話,沒有優秀的技術,隻有适合的技術與不适合的技術。      

繼續閱讀