天天看點

多線程之并發程式設計(一)

一、程序

首先,程序代表運作中的程式,也就是一個Java程式代表一個程序,也可以了解為是一個應用程式。
其次程序包括線程,從開發的角度來看,每一個線程都是程序中可獨立執行的子任務。一個程序包含多個線程。
           

二、線程

在Java中線程分為兩大類:**守護線程** 和 **使用者線程**
守護線程:當程序不存在或主線程停止,守護線程也會被停止,通常守護線程執行一些重要性不是很高的任務(監視其他線程的運作情況)
使用者線程:是使用者自己建立的線程,主線程結束後,使用者不會停止。使用者線程會阻止JVM無法停止。即JVM結束之前所有的使用者線程都必須執行完畢,否則JVM無法停止。
           

三、多線程的建立

多線程的建立分為以下三種:
	繼承Thread類(重寫run方法)、實作Runnable接口(重寫run方法)、通過匿名内部類實作
	一般情況下如果要用以上三種方式實作多線程  建議還是實作Runnable,因為實作了之後還可以繼承别的類,繼承了則不能再次繼承。
           

1、繼承Thread類

class CreateThread extends Thread {
    	// 執行run方法
    	public void run() {
    		for (int i = 0; i< 10; i++) {
    			System.out.println("i:" + i);
    		}
    	}
    }
    public class ThreadDemo {
    	public static void main(String[] args) {
    		System.out.println("<<<<<< 多線程建立開始  >>>>>>");
    		// 1.建立一個線程
    		CreateThread createThread = new CreateThread();
    		// 2.開始執行線程 注意 開啟線程不是調用run方法,而是start方法
    		System.out.println("<<<<<<  多線程建立啟動  >>>>>>");
    		createThread.start();
    		System.out.println("<<<<<<  多線程建立結束  >>>>>>");
    	}
    
    }
           

2、實作Runnable接口

class CreateRunnable implements Runnable {
	@Override
	public void run() {
		for (int i = 0; i< 10; i++) {
			System.out.println("i:" + i);
		}
	}
}
public class ThreadDemo {
	public static void main(String[] args) {
		System.out.println("<<<<<<  多線程建立開始  >>>>>>");
		// 1.建立一個線程
		CreateRunnable createThread = new CreateRunnable();
		// 2.開始執行線程 注意 開啟線程不是調用run方法,而是start方法
		System.out.println("<<<<<<  多線程建立啟動  >>>>>>");
		Thread thread = new Thread(createThread);
		thread.start();
		System.out.println("<<<<<<  多線程建立結束  >>>>>>");
	}
}
           

3、匿名内部類實作

System.out.println("<<<<<<  多線程建立開始  >>>>>>");
		 Thread thread = new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i< 10; i++) {
					System.out.println("i:" + i);
				}
			}
		});
	thread.start();
	System.out.println("<<<<<<  多線程建立結束  >>>>>>");
           

以上是多線程建立的方式,使用多線程的好處可以提高程式效率。一般工作中使用線程池來建立線程,進行統一的線程管理,降低了資源的浪費,提高了相應速度。

不對的地方請指出來 ,謝謝!!!

繼續閱讀