132.繼承Thread實現多執行緒
先寫一個程式碼體會一下多執行緒
通過繼承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");
}
}
程式碼的第一次執行結果:
程式碼的第二次執行結果:
.........每次執行的結果都是不同的
總結一下:執行緒例項建立成功,只是一個執行緒例項,呼叫繼承自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();
}
}
三張圖片都下載成功
…
待學common.jar
Thread
繼承關係
Constructor Summary
Constructor | Description |
---|---|
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 Type | Description |
---|---|
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. |
相關文章
- Java實現多執行緒詳解一 ( 繼承Thread方式 )Java執行緒繼承thread
- Java之實現多執行緒的方式一 :繼承Thread類Java執行緒繼承thread
- python多執行緒之從Thread類繼承Python執行緒thread繼承
- 多執行緒:繼承方式和實現方式的聯絡與區別執行緒繼承
- java多執行緒之Thread類Java執行緒thread
- Java多執行緒(二):Thread類Java執行緒thread
- Java多執行緒Thread類使用Java執行緒thread
- 使用Thread類和Runnable介面實現多執行緒的區別thread執行緒
- Thread(執行緒)thread執行緒
- 多執行緒系列(二)之Thread類執行緒thread
- Java多種方法實現等待所有子執行緒完成再繼續執行Java執行緒
- Swift多執行緒:使用Thread進行多執行緒間通訊,協調子執行緒任務Swift執行緒thread
- 如何實現多執行緒執行緒
- 多執行緒實現多工二執行緒
- 多執行緒實現多工一執行緒
- Java多執行緒之Thread原始碼分析Java執行緒thread原始碼
- Java多執行緒的實現Java執行緒
- Java多執行緒實現方式Java執行緒
- 【unity】 Loom實現多執行緒UnityOOM執行緒
- JavaScript如何實現多執行緒?JavaScript執行緒
- Runnable介面實現多執行緒執行緒
- 多執行緒具體實現執行緒
- Thread 中的 join() 方法的作用是呼叫執行緒等待該執行緒執行完後,再繼續執行thread執行緒
- Python多執行緒之_thread與threading模組Python執行緒thread
- java 多執行緒(關於Thread的講解)Java執行緒thread
- 多執行緒設計模式之Worker Thread模式執行緒設計模式thread
- aardio 實現封裝繼承多型封裝繼承多型
- C語言實現繼承多型C語言繼承多型
- 多執行緒爬蟲實現(上)執行緒爬蟲
- 用Pthread實現多執行緒操作thread執行緒
- 【連載 02】多執行緒實現執行緒
- Android/java 多執行緒(二)-Thread的好兄弟HandlAndroidJava執行緒thread
- EventLoopGroup事件迴圈組(執行緒組)繼承體系OOP事件執行緒繼承
- new Thread與執行緒建立thread執行緒
- Java 中的執行緒 threadJava執行緒thread
- Thread執行緒終止interruptthread執行緒
- Java 多執行緒(Java.Thread)------ 執行緒協作(生產者消費者模式)Java執行緒thread模式
- 多繼承 與 多重繼承繼承