1线程管理
在这一节中,我们将学习如何创建和运行一个线程。在Java语言中,我们有两种方式创建一个线程:
1.扩展Thread类,覆盖run()方法
2.构建一个实现Runnable接口的类,定义自己run()方法,然后,实用则个类的实例对象作为Thread构造方法的参数来创建Thread对象。
创建一个线程对象,它不会创建一个新的执行线程。也就是说,调用一个实现了Runnable接口的类的run()方法,它不会创建一个新的执行线程。仅仅是调用start()方法时,一个新的线程才会被创建。
Thread类保存了一些能够帮助我们标示一个线程的属性信息。
1.ID: 每个线程独一无二的标识符。
2.Name: 存储线程的名称。
3.Priority: 线程对象的优先级属性,其值范围是0到10.除非有特殊要求,一般不推荐修改线程的优先级属性。
4.Status: 这个属性表示线程当前的状态,在Java中,有六种状态:new、runnable
Blocked、time waiting和terminated。
创建一个简单的线程程序。
public class Worker implements Runnable{
private intnumber;
/**
* Constructor of the class
* @param number : The number
*/
public Worker(intnumber) {
this.number=number;
}
/**
* Method that do the calculations
*/
@Override
public voidrun() {
for (int i=1; i<=10; i++){
System.out.printf("%s: %d * %d = %d\n",Thread.currentThread().getName(),number,i,i*number);
}
}
/**
* @param args
*/
public staticvoidmain(String[] args) {
//create 10 thread, chart one
long t1 = System.currentTimeMillis();
for(int i = 0 ; i < 10; i++){
Worker worker = new Worker(i);
Thread thread = new Thread(worker);
thread.start();
}
System.out.println("-----------------------"+(System.currentTimeMillis() - t1));
}
}
在看另一个搜索文件的功能,扫描指定文件目录下的文件。完整代码如下:
import java.io.File;
import java.util.concurrent.TimeUnit;
public class FileSearchRunnable implements Runnable {
/**
* Initial path for the search
*/
private StringinitPath;
/**
* Name of the file we are searching for
*/
private StringfileName;
/**
* Constructor of the class
*
* @param initPath
* : Initial path for the search
* @param fileName
* : Name of the file we are searching for
*/
public FileSearchRunnable(String initPath, String fileName) {
this.initPath = initPath;
this.fileName = fileName;
}
/**
* Main method of the class
*/
@Override
public voidrun() {
File file = new File(initPath);
if (file.isDirectory()) {
try {
directoryProcess(file);
} catch (InterruptedException e) {
System.out.printf("%s: The search has been interrupted",Thread.currentThread().getName());
cleanResources();
}
}
}
/**
* Method for cleaning the resources. In thiscase, is empty
*/
private voidcleanResources() {
}
/**
* Method that process a directory
*
* @param file
* : Directory to process
* @throws InterruptedException
* : If the thread is interrupted
*/
private voiddirectoryProcess(File file) throws InterruptedException {
// Get the content of the directory
File list[] = file.listFiles();
if (list !=null) {
for (int i = 0; i < list.length; i++) {
if (list[i].isDirectory()) {
// If is a directory, process it
directoryProcess(list[i]);
} else {
// If is a file, process it
fileProcess(list[i]);
}
}
}
// Check the interruption
if (Thread.interrupted()) {
throw new InterruptedException();
}
}
/**
* Method that process a File
*
* @param file
* : File to process
* @throws InterruptedException
* : If the thread is interrupted
*/
private voidfileProcess(File file) throws InterruptedException {
System.out.println("current file : "+file.getAbsolutePath());
// Check the name
if (file.getName().equals(fileName)) {
System.out.printf("%s : %s\n",Thread.currentThread().getName(),file.getAbsolutePath());
System.exit(0);
}
// Check the interruption
if (Thread.interrupted()) {
throw new InterruptedException();
}
}
/**
* @param args
*/
public staticvoidmain(String[] args) {
FileSearchRunnable searcher=new FileSearchRunnable("C:\\","USERPRIKEY.HS");
Thread thread=new Thread(searcher);
// Starts the Thread
thread.start();
// Wait for ten seconds
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
分享到:
相关推荐
本资源致力于向您介绍 Java 并发编程中的线程基础,涵盖了多线程编程的核心概念、线程的创建和管理,以及线程间通信的基本方法。通过深入学习,您将建立扎实的多线程编程基础,能够更好地理解和应用多线程编程。 多...
第1章 简介 1.1 并发简史 1.2 线程的优势 1.2.1 发挥多处理器的强大能力 1.2.2 建模的简单性 1.2.3 异步事件的简化处理 1.2.4 响应更灵敏的用户界面 1.3 线程带来的风险 1.3.1 安全性问题 1.3.2 活跃性...
自从java创建以来就已经支持并发的理念,如线程和锁。这篇指南主要是为帮助java多线程开发人员理解并发的核心概念以及如何应用这些理念。本文的主题是关于具有java语言风格的Thread、synchronized、volatile,以及...
并发编程不仅包括多线程,还包括了处理多个独立任务的各种技术和模式,如进程、协程、分布式编程等。并发编程的目标是实现任务的并发执行,以提高系统的性能和资源利用率。 因此,多线程是并发编程的一部分。多线程...
Java并发编程中使用Executors类创建和管理线程的用法共4页.pdf.zip
影响多线程运行速度的原因有线程创建开销、上下文切换、死锁,以及硬件和软件的资源限制等 资源限制:硬件资源和软件资源 硬件资源:如宽带 硬盘读写 内存 cpu处理速度 软件资源:如数据库连接数、socket连接数等 --...
, 本书通过帮助读者理解有关并发编程的模式及其利弊,向读者展示了如何更精确地使用Java平台的线程模型。, 这里,读者将通过使用java.lang.thread类、synchronized和volatile关键字,以及wait、notify和notifyall...
第1章 简介 1.1 并发简史 1.2 线程的优势 1.2.1 发挥多处理器的强大能力 1.2.2 建模的简单性 1.2.3 异步事件的简化处理 1.2.4 响应更灵敏的用户界面 1.3 线程带来的风险 1.3.1 安全性问题 1.3.2 活跃性...
通过深入了解 Java 并发编程和 JUC 线程池,您可以更好地管理线程之间的协作和同步,充分发挥多核处理器的优势,确保程序稳定运行。 了解 Java 并发编程和 JUC 线程池是现代软件开发者的必备知识。通过掌握并发编程...
多种创建线程的方式案例演示(一)带返回值的方式.mp4 多种创建线程的方式案例演示(二)使用线程池.mp4 Spring对并发的支持:Spring的异步任务.mp4 使用jdk8提供的lambda进行并行计算.mp4 了解多线程所带来的安全...
如果你是一名Java开发人员,并且想进一步掌握并发编程和多线程技术,并挖掘Java 7并发的新特性,那么本书是你的合适之选。 《Java 7并发编程实战手册》 第1章 线程管理 1 1.1 简介 1 1.2 线程的创建和运行...
java并发编程脑图总结,线程池、主要使用场景分析,进程:是CPU分配资源的最小单元,是程序的一次动态执行,它对应着从代码加载,执行至完成的一个完整的过程,它有自己的生命周期。它是应用程序的执行实例,每个...
java并发编程 基础知识,守护线程与线程, 并行和并发有什么区别? 什么是上下文切换? 线程和进程区别 什么是线程和进程? 创建线程有哪几种方式?,如何避免线程死锁 线程的 run()和 start()有什么区别? 什么是 ...
龙果 java并发编程原理实战 第2节理解多线程与并发的之间的联系与区别 [免费观看] 00:11:59分钟 | 第3节解析多线程与多进程的联系以及上下文切换所导致资源浪费问题 [免费观看] 00:13:03分钟 | 第4节学习并发的四...
Java并发编程基础主要包括以下几个核心方面: 线程与线程状态:理解Java中线程的基本概念,包括线程的创建、启动、暂停、恢复和终止。熟悉线程的生命周期及其不同状态,如新建、就绪、运行、阻塞和死亡。 线程同步...
Java线程:创建与启动 Java线程:线程栈模型与线程的变量 Java线程:线程状态的转换 Java线程:线程的同步与锁 Java线程:线程的交互 Java线程:线程的调度-休眠 Java线程:线程的调度-优先级 Java线程:线程的调度-...
1、本资源包含并发编程基础知识的使用案例,包括:线程创建、Synchronized和Reentrantlock锁的使用、线程安全问题演示、Condition的应用、CountDownLatch的应用、Cyclicbarrier的应用、Semaphore的应用、线程池的...
这份资源为您提供了关于 Java 并发编程的全面讲解,着重介绍了 JUC(java.util.concurrent)库中的核心概念、工具和最佳实践。通过深入学习,您将能够更好地理解并发编程的挑战,掌握构建高性能、高可伸缩性的并发...
Java并发编程是基于多线程技术的一种编程技术,该技术是为了解决资源利用率、响应速度、线程安全而创建的,能极大的提高程序的运行效率。JUC是指java.util.concurrent这个jdk自带的包的简称,这个包下有Java5发布的...