132.繼承Thread實現多執行緒

雲疏不知數發表於2020-10-06

先寫一個程式碼體會一下多執行緒

通過繼承Thread類實現多執行緒程式碼例項:

package yzy.cn;

public class inheritThread extends Thread{
	private int nums;
	//過載run方法
	@Override
	public void run() {
		super.run();
		for(int i=0; i<nums; ++i)
			System.out.println("singing");
	}
	
	public inheritThread(int nums) {
		super();
		this.nums = nums;
	}

	public static void main(String[] args) {
		int nums = 5;
		//建立執行緒例項
		inheritThread it = new inheritThread(nums);
		//啟動執行緒
		it.start(); //繼承自Thread類
		for(int i=0; i<nums; ++i)
			System.out.println("coding");
	}
}

程式碼的第一次執行結果:

132.繼承Thread實現多執行緒

程式碼的第二次執行結果:

132.繼承Thread實現多執行緒 .........

每次執行的結果都是不同的

總結一下:執行緒例項建立成功,只是一個執行緒例項,呼叫繼承自Thread的start(),才能開啟執行緒,加入到排程器中,等待系統排程分配。從而呼叫覆蓋了Thread基類的run()方法,也就是才呼叫了執行緒體。

再寫一個多執行緒網路下載器,對多執行緒進行更深入的體會

先實現一個網路資源下載器
package yzy.cn;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.FileUtils;

public class webDownloader {
	public void download(String url, String name) {
		//藉助IO工具類對網路URL的資源進行下載,使用外部包common.sjar
		try {
			FileUtils.copyURLToFile(new URL(url), new File(name));
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("不合法的URL");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
然後實現一個類,三個執行緒同時下載三張圖片
package yzy.cn;
/*
 * 開啟三個執行緒同時下載三張圖片
 */
public class inheritThreadToDownloadWebSource extends Thread {
	private String url;
	private String name; //儲存路徑
	
	public inheritThreadToDownloadWebSource(String url, String name) {
		super();
		this.url = url;
		this.name = name;
	}
	
	public void run() {
		webDownloader wd = new webDownloader();
		wd.download(url, name);
	}
	public static void main(String[] args) {
		//建立三個執行緒例項
		inheritThreadToDownloadWebSource i1 = new inheritThreadToDownloadWebSource(
				"https://img-blog.csdnimg.cn/20200719183823584.png", "位元組流.png");
		inheritThreadToDownloadWebSource i2 = new inheritThreadToDownloadWebSource(
				"https://img-blog.csdnimg.cn/20200719183720714.png", "字元流.png");
		inheritThreadToDownloadWebSource i3 = new inheritThreadToDownloadWebSource(
				"https://img-blog.csdnimg.cn/20200719180355134.png", "輸入輸出關係.png");
		
		//啟動三個執行緒
		i1.start();
		i2.start();
		i3.start();
	}
}
三張圖片都下載成功
132.繼承Thread實現多執行緒

待學common.jar

Thread

繼承關係
132.繼承Thread實現多執行緒
Constructor Summary
ConstructorDescription
Thread()Allocates a new Thread object.
Thread(Runnable target)Allocates a new Thread object.
Thread(Runnable target, String name)Allocates a new Thread object.
Thread(String name)Allocates a new Thread object.
Thread(ThreadGroup group, Runnable target)Allocates a new Thread object.
Thread(ThreadGroup group, Runnable target, String name)Allocates a new Thread object so that it has target as its run object, has the
Thread(ThreadGroup group, Runnable target, String name, long stackSize)Allocates a new Thread object so that it has target as its run object, has the
Thread(ThreadGroup group, Runnable target, String name, long stackSize, boolean inheritThreadLocals)Allocates a new Thread object so that it has target as its run object, has the specified name as its name, belongs to the thread group referred to by group, has the specified stackSize, and inherits initial values for inheritable thread-local
Thread(ThreadGroup group, String name)Allocates a new Thread object.
Method Summary
Method Modifier and TypeDescription
static int activeCount()Returns an estimate of the number of active threads in the current thread’s thread group and its subgroups.
void checkAccess()Determines if the currently running thread has permission to modify this thread.
protected Object clone()Throws CloneNotSupportedException as a Thread can not be meaningfully cloned.
int countStackFrames()Deprecated, for removal: This API element is subject to removal in a future version.This method was originally designed to count the number of stack frames but the results were never well-defined and it depended on thread-suspension.
static Thread currentThread()Returns a reference to the currently executing thread object.
static void dumpStack()Prints a stack trace of the current thread to the standard error stream.
static int enumerate(Thread[] tarray)Copies into the specified array every active thread in the current thread’s thread group and its subgroups.
static Map < Thread, StackTraceElement[]> getAllStackTraces()Returns a map of stack traces for all live threads.
ClassLoader getContextClassLoader()Returns the context ClassLoader for this thread.
static Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()Returns the default handler invoked when a thread abruptly terminates due to an uncaught exception.
long getId()Returns the identifier of this Thread.
String getName()Returns this thread’s name.
int getPriority()Returns this thread’s priority.
StackTraceElement[] getStackTrace()Returns an array of stack trace elements representing the stack dump of this thread.
Thread.State getState()Returns the state of this thread.
ThreadGroup getThreadGroup()Returns the thread group to which this thread belongs.
Thread.UncaughtExceptionHandler getUncaughtExceptionHandler()Returns the handler invoked when this thread abruptly terminates due to an uncaught exception.
static boolean holdsLock(Object obj)Returns true if and only if the current thread holds the monitor lock on the specified object.
void interrupt()Interrupts this thread.
static boolean interrupted()Tests whether the current thread has been interrupted.
boolean isAlive()Tests if this thread is alive.
boolean isDaemon()Tests if this thread is a daemon thread.
boolean isInterrupted()Tests whether this thread has been interrupted.
void join()Waits for this thread to die.
void join(long millis)Waits at most millis milliseconds for this thread to die.
void join(long millis, int nanos)Waits at most millis milliseconds plus nanos nanoseconds for this thread to die.
static void onSpinWait()Indicates that the caller is momentarily unable to progress, until the occurrence of one or more actions on the part of other activities.
void resume()Deprecated, for removal: This API element is subject to removal in a future version.This method exists solely for use with suspend(), which has been deprecated because it is deadlock-prone.
void run()If this thread was constructed using a separate Runnable run object, then that Runnable object’s run method is called; otherwise, this method does nothing and returns.
void setContextClassLoader(ClassLoader cl)Sets the context ClassLoader for this Thread.
void setDaemon(boolean on)Marks this thread as either a daemon thread or a user thread.
static void setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh)Set the default handler invoked when a thread abruptly terminates due to an uncaught exception, and no other handler has been defined for that thread.
void setName(String name)Changes the name of this thread to be equal to the argument name.
void setPriority(int newPriority)Changes the priority of this thread.
void setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh)Set the handler invoked when this thread abruptly terminates due to an uncaught exception.
static void sleep(long millis)Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
static void sleep(long millis, int nanos)Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds plus the specified number of nanoseconds, subject to the precision and accuracy of system timers and schedulers.
void start()Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
void stop()Deprecated. This method is inherently unsafe.
void suspend()Deprecated, for removal: This API element is subject to removal in a future version.This method has been deprecated, as it is inherently deadlock-prone.
String toString()Returns a string representation of this thread, including the thread’s name, priority, and thread group.
static void yield()A hint to the scheduler that the current thread is willing to yield its current use of a processor.

相關文章