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");
	}
}

代码的第一次执行结果:

132.继承Thread实现多线程_第1张图片

代码的第二次执行结果:

132.继承Thread实现多线程_第2张图片 .........

每次执行的结果都是不同的

总结一下:线程实例创建成功,只是一个线程实例,调用继承自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实现多线程_第3张图片

待学common.jar

Thread

继承关系
132.继承Thread实现多线程_第4张图片
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)