Java多线程Thread基础学习
作者:lmrylll 发布时间:2023-04-17 17:12:21
1. 创建线程
1.1 通过构造函数:public Thread(Runnable target, String name){} 或:public Thread(Runnable target){}
示例:
Thread thread1 = new Thread(new MyThread(), "mythread");
class MyThread extends Thread(){
public void run(){
System.out.println("My First Thread');
}
}
1.2 直接实现Runnable接口:
示例:
Thread thread2 = new Thread(new Runnable{}{
public void run(){
System.out.println("This is my thread.");
}
});
2. 运行线程
thead1.start()
3. sleep
try{
#休眠1000ms
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
4. getName() 获取线程名字, getId()获取线程id
System.out.println(Thread.currentThread().getName() + ":"+ Thread.currentThread().getId);
5. 停止线程,
千万不用stop(),stop会立即终止线程。
通过interrupt()中断线程,但是中断并没有停止线程,配合异常来实现:
public class Main {
public static void main(String[] args) throws InterruptedException {
try{
Thread thread1=new Thread(new TheThread(),"thread1");
thread1.start();
Thread.sleep(2000);
thread1.interrupt();
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
class TheThread extends Thread{
public void run() {
super.run();
for (int i = 0; i < 10; i++) {
if(this.interrupted()){
break;
}
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
注意,如果在TheThread类里加入catch InterruptException的话,可能会导致interrupt被捕获,而绕过if(this.interrupted())的判断而无法终止线程。
6. 等待和通知
线程等待:当前线程就处于等待状态,直到其他线程调用了notify()方法,线程才会继续执行
public final void wait() throws InterruptedException
线程通知:
public final native void notify()
注意:在notify()方法后,当前线程不会马上释放该对象锁,要等到执行notify()方法的线程将程序执行完,也就是退出同步代码块中。
package wait.notify;
public class ThreadWaitNotifyTest {
final static Object object=new Object();
public static class T1 extends Thread{
public void run(){
System.out.println(System.currentTimeMillis()+": T1 start");
synchronized (object){
try {
System.out.println(System.currentTimeMillis()+": T1 wait");
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(System.currentTimeMillis()+": T1 end");
}
}
public static class T2 extends Thread{
public void run(){
System.out.println(System.currentTimeMillis()+": T2 start");
synchronized (object){
System.out.println("T2 synchonized code start.");
object.notify();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
System.out.println("T2 synchonized code end.");
}
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis()+": T2 end");
}
}
public static void main(String[] args){
Thread thread1=new T1();
Thread thread2=new T2();
thread1.start();
thread2.start();
}
}
输出结果:
7. 线程优先级
高优先级的线程将会获得更多的CPU资源。一共分为10个优先级。
public final void setPriority(int newPriority)
源码分析:
public final void setPriority(int newPriority) {
ThreadGroup g;
checkAccess();
if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
throw new IllegalArgumentException();
}
if((g = getThreadGroup()) != null) {
if (newPriority > g.getMaxPriority()) {
newPriority = g.getMaxPriority();
}
setPriority0(priority = newPriority);
}
}
public final static int MIN_PRIORITY = 1;
public final static int NORM_PRIORITY = 5;
public final static int MAX_PRIORITY = 10;
可见线程最高优先级为10, 最低为1, 默认为5.
当设定的newPriority高于该线程组ThreadGroup的最高Priority时,只能分配该线程组的最高Priority
8. 守护线程
类似守护进程,Java存在两种线程:用户线程和守护线程。它是一种特殊线程,执行的是一种后台服务,当一个系统中不存在非守护线程的时候,守护线程会自己销毁。典型的守护线程:JVM的垃圾回收线程。
public final void setDaemon(boolean on)
示例:
public class Main {
public static void main(String[] args) throws InterruptedException {
TheThread theThread=new TheThread();
theThread.setDaemon(true);//设置守护线程
theThread.start();
Thread.sleep(5000);
System.out.println("全都退出啦");
}
public static class TheThread extends Thread{
public void run(){
int i = 0;
while (true){
i++;
System.out.println(Thread.currentThread().getId()+":"+i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
源码分析:
设置线程为用户线程(user thread)或守护线程(daemon thread),当剩余运行的线程均为守护线程时,JVM会退出。
public final void setDaemon(boolean on) {
checkAccess();
if (isAlive()) {
throw new IllegalThreadStateException();
}
daemon = on;
}
其中checkAccesss()方法如下:
public final void checkAccess() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkAccess(this);
}
}
该方法用于判断当前运行的线程是否有修改此线程的权限。
而public final native boolean isAlive();用于判断该线程是否处于alive状态,即该线程是否已经start,且没有die。
当isAlive的话就会抛出IllegalThreadStateException异常。
所以,设置守护线程的方法,逻辑就是先判断当前线程是否有修改的权限,再判断是否处于alive状态,如果不处于alive状态,则根据boolean变量on的值更改它的状态,即true:设为daemon线程,false:设为user线程。
来源:https://blog.csdn.net/lmrylll/article/details/130181975


猜你喜欢
- 这篇文章主要介绍了SpringBoot文件访问映射如何实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要
- 在Controller层时,往往会需要校验或验证某些操作,而在每个Controller写重复代码,工作量比较大,这里在Springboot项
- 一、HandlerThread的介绍及使用举例  
- 先看看效果图:package wuwang.tools.utils; import java.io.File; import java.io
- 【程序1】 题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少? 1.程序分析:可填在百位、十位、个位的数字都
- 页面提交请求参数有两种,一种是form格式提交,一种json格式提交通常情况下我们使用的都是form格式提交的数据,数据格式:k=v&
- Servlet简介servlet是Server Applet的简称,翻译过来就是服务程序.好吧,这么说你可能还是不太懂,简单的讲,这个ser
- WebServiceHelper代码:using Microsoft.CSharp;using System;using System.Co
- 获取最新插入数据的id原始方法读取最后一条的插入数据,但这样会造成如果两条数据同时插入,会并发出现错误SELECT * FROM admin
- 一、HTTP http请求 一般一个http请求包括以下三个部分: 1 请求方法,如get,pos
- 前言当我们编写 C# 代码时,经常需要处理大量的数据集合。在传统的方式中,我们往往需要先将整个数据集合加载到内存中,然后再进行操作。但是如果
- 通过继承Thread类并实现run方法创建一个线程// 定义一个Thread类,相当于一个线程的模板class MyThread01 ext
- Java中的final关键字1、修饰类的成员变量 这是final的主要用途之一,和C/C++的const,即该成员被修饰为常量,意味着不可修
- 查找应用进程PID杀死应用进程PID运行启动脚本烦不烦啊,像我这么懒得人 得想个办法一步搞定!如下所示 新建一个shell脚本,然后将其运行
- 一、常见的状态保存恢复方式①onSaveInstance + onRestoreInstance这种方式是最通用的实现状态保存与恢复,在An
- 本文实例讲述了C#中使用ADOMD.NET查询多维数据集的实现方法,分享给大家供大家参考。具体实现方法分析如下:ADOMD.NET 是用于与
- Java 中的内部类这是一个 Java 内部类的简单实现:public class OutterJava { pr
- 各位相加给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。示例:输入: 38输出: 2 解释: 各位相加的过程
- 环境:apache-tomcat-8.5.15jdk1.8.0_172IDEA建立一个maven-webapp项目:Create New P
- 前言:Java异常处理的五个关键字:try、catch、finally、throw、throws抛出异常throw在编写程序时,我们必须要考