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
猜你喜欢
- makeCertPic.javapackage pic;import java.awt.Color;import java.awt.Font
- 本人一直使用的是Eclipse作为开发工具的,不过现在IDEA非常的受推崇,所以决定上手试一试。网上有很多旗舰版的文章,我没有仔细看,我这次
- 本文实例分析了java中transient关键字用法。分享给大家供大家参考。具体分析如下:java有个特点就是序列化,简单地来说就是可以将这
- 本文实例讲述了Spring使用ClassPathResource加载xml资源。分享给大家供大家参考,具体如下:一 代码package le
- 目录Java反射超详解1.反射基础1.1Class类1.2类加载2.反射的使用2.1Class对象的获取 2.2Construct
- 本文实例为大家分享了flutter实现倒计时加载页面的具体代码,供大家参考,具体内容如下效果图实现步骤1、pubspec.yaml中添加依赖
- Java 中的 BIO、NIO和 AIO 理解为是 Java 语言对操作系统的各种 IO 模型的封装。程序员在使用这些 API 的时候,不需
- #简易版1、客户发送请求经过 DisPatcherServlet 核心过滤器2、DisPatcherServlet 核心控制器在去找一个或多
- JVM 的主要作用是什么?JVM 就是 Java Virtual Machine(Java虚拟机)的缩写,JVM 屏蔽了与具体操作系统平台相
- 初次安装Android Studio,遇到了不少问题,这是其中的一个,分享如下,同时求各位dalao关注一下啦((*^__^*) )使用不同
- 详解Java注解的实现与使用方法Java注解是java5版本发布的,其作用就是节省配置文件,增强代码可读性。在如今各种框架及开发中非常常见,
- 一个Java程序的执行要经过编译和执行(解释)这两个步骤,同时Java又是面向对象的编程语言。当子类和父类存在同一个方法,子类重写了父类的方
- JDK 1.5开始提供ScheduledThreadPoolExecutor类,ScheduledThreadPoolExecutor类继承
- mybatis自动生成实体类、mapper文件、mapper.xml文件若采用mybatis框架,数据库新建表,手动编写的话,需要编写大量的
- 本文实例讲述了Java基于Tcp的基础聊天功能。分享给大家供大家参考,具体如下:最基础的聊天,用户端和服务器端每次说一句,而且严格规定了先后
- 下面是一个邮件接收的工具类,有点长!!!public class ReciveMail { private MimeMessage msg
- 昨天在与对端系统调接口的时候,对端系统对我们传过去的json串老是处理不了,后来查原因是应为我们传过去的json串里有json对象数组,因为
- 1.设置url-pattern为*.do(最为常见的方式)只要你的请求url中包含配置的url-pattern,该url就可以到达Dispa
- 1、 定义头和根元素部署描述符文件就像所有XML文件一样,必须以一个XML头开始。这个头声明可以使用的XML版本并给出文件的字符编码。DOC
- 下面本文将针对以上几点问题进行描述讨论,我们就以“中文”两个字为例来说明,查找相关资料可知“中文”的GB2312编码是“d6d0 cec4”