Java回顾之多线程
在这篇文章里,我们关注多线程。多线程是一个复杂的话题,包含了很多内容,这篇文章主要关注线程的基本属性、如何创建线程、线程的状态切换以及线程通信,我们把线程同步的话题留到下一篇文章中。
线程是操作系统运行的基本单位,它被封装在进程中,一个进程可以包含多个线程。即使我们不手动创造线程,进程也会有一个默认的线程在运行。
对于JVM来说,当我们编写一个单线程的程序去运行时,JVM中也是有至少两个线程在运行,一个是我们创建的程序,一个是垃圾回收。
线程基本信息
我们可以通过Thread.currentThread()方法获取当前线程的一些信息,并对其进行修改。
我们来看以下代码:
String name = Thread.currentThread().getName();
int priority = Thread.currentThread().getPriority();
String groupName = Thread.currentThread().getThreadGroup().getName();
boolean isDaemon = Thread.currentThread().isDaemon();
System.out.println("Thread Name:" + name);
System.out.println("Priority:" + priority);
System.out.println("Group Name:" + groupName);
System.out.println("IsDaemon:" + isDaemon); Thread.currentThread().setName("Test");
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
name = Thread.currentThread().getName();
priority = Thread.currentThread().getPriority();
groupName = Thread.currentThread().getThreadGroup().getName();
isDaemon = Thread.currentThread().isDaemon();
System.out.println("Thread Name:" + name);
System.out.println("Priority:" + priority);
其中列出的属性说明如下:
- GroupName,每个线程都会默认在一个线程组里,我们也可以显式的创建线程组,一个线程组中也可以包含子线程组,这样线程和线程组,就构成了一个树状结构。
- Name,每个线程都会有一个名字,如果不显式指定,那么名字的规则是“Thread-xxx”。
- Priority,每个线程都会有自己的优先级,JVM对优先级的处理方式是“抢占式”的。当JVM发现优先 级高的线程时,马上运行该线程;对于多个优先级相等的线程,JVM对其进行轮询处理。Java的线程优先级从1到10,默认是5,Thread类定义了2 个常量:MIN_PRIORITY和MAX_PRIORITY来表示最高和最低优先级。
我们可以看下面的代码,它定义了两个不同优先级的线程:public static void priorityTest()
{
Thread thread1 = new Thread("low")
{
public void run()
{
for (int i = 0; i < 5; i++)
{
System.out.println("Thread 1 is running.");
}
}
}; Thread thread2 = new Thread("high")
{
public void run()
{
for (int i = 0; i < 5; i++)
{
System.out.println("Thread 2 is running.");
}
}
}; thread1.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.MAX_PRIORITY);
thread1.start();
thread2.start();
}从运行结果可以看出,是高优先级线程运行完成后,低优先级线程才运行。
- isDaemon,这个属性用来控制父子线程的关系,如果设置为true,当父线程结束后,其下所有子线程也结束,反之,子线程的生命周期不受父线程影响。
我们来看下面的例子:public static void daemonTest()
{
Thread thread1 = new Thread("daemon")
{
public void run()
{
Thread subThread = new Thread("sub")
{
public void run()
{
for(int i = 0; i < 100; i++)
{
System.out.println("Sub Thread Running " + i);
}
}
};
subThread.setDaemon(true);
subThread.start();
System.out.println("Main Thread end.");
}
}; thread1.start();
}上面代码的运行结果,在和删除subThread.setDaemon(true);后对比,可以发现后者运行过程中子线程会完成执行后再结束,而前者中,子线程很快就结束了。
如何创建线程
上面的内容,都是演示默认线程中的一些信息,那么应该如何创建线程呢?在Java中,我们有3种方式可以用来创建线程。
Java中的线程要么继承Thread类,要么实现Runnable接口,我们一一道来。
使用内部类来创建线程
我们可以使用内部类的方式来创建线程,过程是声明一个Thread类型的变量,并重写run方法。示例代码如下:
public static void createThreadByNestClass()
{
Thread thread = new Thread()
{
public void run()
{
for (int i =0; i < 5; i++)
{
System.out.println("Thread " + Thread.currentThread().getName() + " is running.");
}
System.out.println("Thread " + Thread.currentThread().getName() + " is finished.");
}
};
thread.start();
}
继承Thread以创建线程
我们可以从Thread中派生一个类,重写其run方法,这种方式和上面相似。示例代码如下:
class MyThread extends Thread
{
public void run()
{
for (int i =0; i < 5; i++)
{
System.out.println("Thread " + Thread.currentThread().getName() + " is running.");
}
System.out.println("Thread " + Thread.currentThread().getName() + " is finished.");
}
} public static void createThreadBySubClass()
{
MyThread thread = new MyThread();
thread.start();
}
实现Runnable接口以创建线程
我们可以定义一个类,使其实现Runnable接口,然后将该类的实例作为构建Thread变量构造函数的参数。示例代码如下:
class MyRunnable implements Runnable
{
public void run()
{
for (int i =0; i < 5; i++)
{
System.out.println("Thread " + Thread.currentThread().getName() + " is running.");
}
System.out.println("Thread " + Thread.currentThread().getName() + " is finished.");
}
} public static void createThreadByRunnable()
{
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
上述3种方式都可以创建线程,而且从示例代码上看,线程执行的功能是一样的,那么这三种创建方式有什么不同呢?
这涉及到Java中多线程的运行模式,对于Java来说,多线程在运行时,有“多对象多线程”和“单对象多线程”的区别:
- 多对象多线程,程序在运行过程中创建多个线程对象,每个对象上运行一个线程。
- 单对象多线程,程序在运行过程中创建一个线程对象,在其上运行多个线程。
显然,从线程同步和调度的角度来看,多对象多线程要简单一些。上述3种线程创建方式,前两种都属于“多对象多线程”,第三种既可以使用“多对象多线程”,也可以使用“单对象单线程”。
我们来看下面的示例代码,里面会用到Object.notify方法,这个方法会唤醒对象上的一个线程;而Object.notifyAll方法,则会唤醒对象上的所有线程。
public class NotifySample { public static void main(String[] args) throws InterruptedException
{
notifyTest();
notifyTest2();
notifyTest3();
} private static void notifyTest() throws InterruptedException
{
MyThread[] arrThreads = new MyThread[3];
for (int i = 0; i < arrThreads.length; i++)
{
arrThreads[i] = new MyThread();
arrThreads[i].id = i;
arrThreads[i].setDaemon(true);
arrThreads[i].start();
}
Thread.sleep(500);
for (int i = 0; i < arrThreads.length; i++)
{
synchronized(arrThreads[i])
{
arrThreads[i].notify();
}
}
} private static void notifyTest2() throws InterruptedException
{
MyRunner[] arrMyRunners = new MyRunner[3];
Thread[] arrThreads = new Thread[3];
for (int i = 0; i < arrThreads.length; i++)
{
arrMyRunners[i] = new MyRunner();
arrMyRunners[i].id = i;
arrThreads[i] = new Thread(arrMyRunners[i]);
arrThreads[i].setDaemon(true);
arrThreads[i].start();
}
Thread.sleep(500);
for (int i = 0; i < arrMyRunners.length; i++)
{
synchronized(arrMyRunners[i])
{
arrMyRunners[i].notify();
}
}
} private static void notifyTest3() throws InterruptedException
{
MyRunner runner = new MyRunner();
Thread[] arrThreads = new Thread[3];
for (int i = 0; i < arrThreads.length; i++)
{
arrThreads[i] = new Thread(runner);
arrThreads[i].setDaemon(true);
arrThreads[i].start();
}
Thread.sleep(500); synchronized(runner)
{
runner.notifyAll();
}
}
} class MyThread extends Thread
{
public int id = 0;
public void run()
{
System.out.println("第" + id + "个线程准备休眠5分钟。");
try
{
synchronized(this)
{
this.wait(5*60*1000);
}
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
System.out.println("第" + id + "个线程被唤醒。");
}
} class MyRunner implements Runnable
{
public int id = 0;
public void run()
{
System.out.println("第" + id + "个线程准备休眠5分钟。");
try
{
synchronized(this)
{
this.wait(5*60*1000);
}
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
System.out.println("第" + id + "个线程被唤醒。");
} }
示例代码中,notifyTest()和notifyTest2()是“多对象多线程”,尽管notifyTest2()中的线程实现了 Runnable接口,但是它里面定义Thread数组时,每个元素都使用了一个新的Runnable实例。notifyTest3()属于“单对象多线 程”,因为我们只定义了一个Runnable实例,所有的线程都会使用这个实例。
notifyAll方法适用于“单对象多线程”的情景,因为notify方法只会随机唤醒对象上的一个线程。
线程的状态切换
对于线程来讲,从我们创建它一直到线程运行结束,在这个过程中,线程的状态可能是这样的:
- 创建:已经有Thread实例了, 但是CPU还有为其分配资源和时间片。
- 就绪:线程已经获得了运行所需的所有资源,只等CPU进行时间调度。
- 运行:线程位于当前CPU时间片中,正在执行相关逻辑。
- 休眠:一般是调用Thread.sleep后的状态,这时线程依然持有运行所需的各种资源,但是不会被CPU调度。
- 挂起:一般是调用Thread.suspend后的状态,和休眠类似,CPU不会调度该线程,不同的是,这种状态下,线程会释放所有资源。
- 死亡:线程运行结束或者调用了Thread.stop方法。
下面我们来演示如何进行线程状态切换,首先我们会用到下面方法:
- Thread()或者Thread(Runnable):构造线程。
- Thread.start:启动线程。
- Thread.sleep:将线程切换至休眠状态。
- Thread.interrupt:中断线程的执行。
- Thread.join:等待某线程结束。
- Thread.yield:剥夺线程在CPU上的执行时间片,等待下一次调度。
- Object.wait:将Object上所有线程锁定,直到notify方法才继续运行。
- Object.notify:随机唤醒Object上的1个线程。
- Object.notifyAll:唤醒Object上的所有线程。
下面,就是演示时间啦!!!
线程等待与唤醒
这里主要使用Object.wait和Object.notify方法,请参见上面的notify实例。需要注意的是,wait和notify 都必须针对同一个对象,当我们使用实现Runnable接口的方式来创建线程时,应该是在Runnable对象而非Thread对象上使用这两个方法。
线程的休眠与唤醒
public class SleepSample { public static void main(String[] args) throws InterruptedException
{
sleepTest();
} private static void sleepTest() throws InterruptedException
{
Thread thread = new Thread()
{
public void run()
{
System.out.println("线程 " + Thread.currentThread().getName() + "将要休眠5分钟。");
try
{
Thread.sleep(5*60*1000);
}
catch(InterruptedException ex)
{
System.out.println("线程 " + Thread.currentThread().getName() + "休眠被中断。");
}
System.out.println("线程 " + Thread.currentThread().getName() + "休眠结束。");
}
};
thread.setDaemon(true);
thread.start();
Thread.sleep(500);
thread.interrupt();
} }
线程在休眠过程中,我们可以使用Thread.interrupt将其唤醒,这时线程会抛出InterruptedException。
线程的终止
虽然有Thread.stop方法,但该方法是不被推荐使用的,我们可以利用上面休眠与唤醒的机制,让线程在处理IterruptedException时,结束线程。
public class StopThreadSample { public static void main(String[] args) throws InterruptedException
{
stopTest();
} private static void stopTest() throws InterruptedException
{
Thread thread = new Thread()
{
public void run()
{
System.out.println("线程运行中。");
try
{
Thread.sleep(1*60*1000);
}
catch(InterruptedException ex)
{
System.out.println("线程中断,结束线程");
return;
}
System.out.println("线程正常结束。");
}
};
thread.start();
Thread.sleep(500);
thread.interrupt();
}
}
线程的同步等待
当我们在主线程中创建了10个子线程,然后我们期望10个子线程全部结束后,主线程在执行接下来的逻辑,这时,就该Thread.join登场了。
public class JoinSample { public static void main(String[] args) throws InterruptedException
{
joinTest();
} private static void joinTest() throws InterruptedException
{
Thread thread = new Thread()
{
public void run()
{
try
{
for(int i = 0; i < 5; i++)
{
System.out.println("线程在运行。");
Thread.sleep(1000);
}
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
};
thread.setDaemon(true);
thread.start();
Thread.sleep(1000);
thread.join();
System.out.println("主线程正常结束。");
}
}
我们可以试着将thread.join();注释或者删除,再次运行程序,就可以发现不同了。
线程间通信
我们知道,一个进程下面的所有线程是共享内存空间的,那么我们如何在不同的线程之间传递消息呢?在回顾 Java I/O时,我们谈到了PipedStream和PipedReader,这里,就是它们发挥作用的地方了。
下面的两个示例,功能完全一样,不同的是一个使用Stream,一个使用Reader/Writer。
public static void communicationTest() throws IOException, InterruptedException
{
final PipedOutputStream pos = new PipedOutputStream();
final PipedInputStream pis = new PipedInputStream(pos); Thread thread1 = new Thread()
{
public void run()
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try
{
while(true)
{
String message = br.readLine();
pos.write(message.getBytes());
if (message.equals("end")) break;
}
br.close();
pos.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}; Thread thread2 = new Thread()
{
public void run()
{
byte[] buffer = new byte[1024];
int bytesRead = 0;
try
{
while((bytesRead = pis.read(buffer, 0, buffer.length)) != -1)
{
System.out.println(new String(buffer));
if (new String(buffer).equals("end")) break;
buffer = null;
buffer = new byte[1024];
}
pis.close();
buffer = null;
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}; thread1.setDaemon(true);
thread2.setDaemon(true);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
}
private static void communicationTest2() throws InterruptedException, IOException
{
final PipedWriter pw = new PipedWriter();
final PipedReader pr = new PipedReader(pw);
final BufferedWriter bw = new BufferedWriter(pw);
final BufferedReader br = new BufferedReader(pr); Thread thread1 = new Thread()
{
public void run()
{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try
{
while(true)
{
String message = br.readLine();
bw.write(message);
bw.newLine();
bw.flush();
if (message.equals("end")) break;
}
br.close();
pw.close();
bw.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}; Thread thread2 = new Thread()
{
public void run()
{ String line = null;
try
{
while((line = br.readLine()) != null)
{
System.out.println(line);
if (line.equals("end")) break;
}
br.close();
pr.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}; thread1.setDaemon(true);
thread2.setDaemon(true);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
}
Java回顾之多线程的更多相关文章
- Java回顾之多线程同步
在这篇文章里,我们关注线程同步的话题.这是比多线程更复杂,稍不留意,我们就会“掉到坑里”,而且和单线程程序不同,多线程的错误是否每次都出现,也是不固定的,这给调试也带来了很大的挑战. 在这篇文章里,我 ...
- Java回顾之Spring基础
第一篇:Java回顾之I/O 第二篇:Java回顾之网络通信 第三篇:Java回顾之多线程 第四篇:Java回顾之多线程同步 第五篇:Java回顾之集合 第六篇:Java回顾之序列化 第七篇:Java ...
- 0037 Java学习笔记-多线程-同步代码块、同步方法、同步锁
什么是同步 在上一篇0036 Java学习笔记-多线程-创建线程的三种方式示例代码中,实现Runnable创建多条线程,输出中的结果中会有错误,比如一张票卖了两次,有的票没卖的情况,因为线程对象被多条 ...
- Java学习笔记-多线程-创建线程的方式
创建线程 创建线程的方式: 继承java.lang.Thread 实现java.lang.Runnable接口 所有的线程对象都是Thead及其子类的实例 每个线程完成一定的任务,其实就是一段顺序执行 ...
- Java线程与多线程教程
本文由 ImportNew - liken 翻译自 Journaldev. Java线程是执行某些任务的轻量级进程.Java通过Thread类提供多线程支持,应用可以创建并发执行的多个线程. 应用 ...
- Java面试题-多线程
1. java中有几种方法可以实现一个线程? 多线程有两种实现方法,分别是继承Thread类与实现Runnable接口. 这两种方法的区别是,如果你的类已经继承了其它的类,那么你只能选择实现Runna ...
- Java面试09|多线程
1.假如有Thread1.Thread2.Thread3.Thread4四条线程分别统计C.D.E.F四个盘的大小,所有线程都统计完毕交给Thread5线程去做汇总,应当如何实现? 把相互独立的计算任 ...
- Java 中传统多线程
目录 Java 中传统多线程 线程初识 线程的概念 实现线程 线程的生命周期 常用API 线程同步 多线程共享数据的问题 线程同步及实现机制 线程间通讯 线程间通讯模型 线程中通讯的实现 @(目录) ...
- 2019/3/7 Java学习之多线程(基础)
Java学习之多线程 讲到线程,就必须要懂得进程,进程是相当于一个程序的开始到结束,而线程是依赖于进程的,没有进程,就没有线程.线程也分主线程和子线程,当在主线程开启子线程时,主线程结束,而子线程还可 ...
随机推荐
- BFS+优先队列+状态压缩DP+TSP
http://acm.hdu.edu.cn/showproblem.php?pid=4568 Hunter Time Limit: 2000/1000 MS (Java/Others) Memo ...
- POI各Jar包的作用(转)
目前POI的最新发布版本是3.10_FINAL.该版本保护的jar包有: Maven artifactId Prerequisites JAR poi commons-logging, commons ...
- SQL中 decode()函数简介(转载)
今天看别人的SQL时看这里面还有decode()函数,以前从来没接触到,上网查了一下,还挺好用的一个函数,写下来希望对朋友们有帮助哈! decode()函数简介: 主要作用:将查询结果翻译成其他值(即 ...
- 170712、springboot编程之集成shiro
这篇文章我们来学习如何使用Spring Boot集成Apache Shiro.安全应该是互联网公司的一道生命线,几乎任何的公司都会涉及到这方面的需求.在Java领域一般有Spring Security ...
- 括号匹配问题(区间dp)
简单的检查括号是否配对正确使用的是栈模拟,这个不必再说,现在将这个问题改变一下:如果给出一个括号序列,问需要把他补全成合法最少需要多少步? 这是一个区间dp问题,我们可以利用区间dp来解决,直接看代码 ...
- Oracle HA 之 基于活动数据库复制配置oracle 11.2 dataguard
规划:主库:db_name=dbking db_unique_name=dbkingpri 备库:db_name=dbking ...
- Pycharm一直报ImportError: No module named requests
1.首先检查是否安装了requests l 安装命令:pip install requests如果出现了Requirement already satisfied 代表安装成功 2.系统含有多个版本的 ...
- 修改字段字符集 mysql 修改 锁表 show processlist; 查看进程 Waiting for table metadata lock
ALTER TABLE `question` MODIFY COLUMN `title` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unico ...
- Scanline Fill Algorithm
https://www.sccs.swarthmore.edu/users/02/jill/graphics/hw3/hw3.html http://web.cs.ucdavis.edu/~ma/EC ...
- talib 中文文档(十五):Math Operator Functions 数学方法
Math Operator Functions 数学运算符函数 ADD - Vector Arithmetic Add 函数名:ADD 名称:向量加法运算 real = ADD(high, low) ...