20240423-线程基础

创建线程的三种方法

继承Thread

java 复制代码
package com.ysf;

import java.util.concurrent.TimeUnit;

public class ThreadWay {

    public static void main(String[] args) throws InterruptedException {
        Hello t = new Hello();
        t.start();
        TimeUnit.SECONDS.sleep(3L);
    }

    static class Hello extends Thread{
        public void run(){
            System.out.println("hello");
        }
    }
}

实现Runnable

java 复制代码
package com.ysf;

import java.util.concurrent.TimeUnit;

public class RunableWay {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new Test());
        thread.start();
        TimeUnit.SECONDS.sleep(10L);
    }

    static class Test implements Runnable{

        public void run() {
            System.out.println("hello");
        }
    }
}

实现Callable使用FutureTask

java 复制代码
package com.ysf;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class CallableWay {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<Integer> task = new FutureTask<>(new Tst());
        Thread thread = new Thread(task);
        thread.start();
        System.out.println(task.get());
    }

    static class Tst implements Callable<Integer>{

        public Integer call() throws Exception {
            int a = 0;
            for (int i=0;i<100;i++){
                a +=i;
            }
            return a;
        }
    }
}

线程的状态

NEW状态

java 复制代码
package com.ysf;

public class Tst01NEWState {

    public static void main(String[] args) {
        Thread t = new Thread(()->{});
        System.out.println(t.getState());
    }
}

RUNNABLE状态

java 复制代码
package com.ysf;

import java.util.concurrent.TimeUnit;

public class Tst02RUNNABLEState {

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(()->{
            while (true){}
        });
        t.start();
        TimeUnit.SECONDS.sleep(20L);
        System.out.println(t.getState());
    }
}

BLOCKED状态

java 复制代码
package com.ysf;

import java.util.concurrent.TimeUnit;

public class Tst03BLOCKState {

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(()->{
            // t线程在获取锁的时候阻塞,因为锁已经被主线程拿走了
           synchronized (Tst03BLOCKState.class){

           }
        });

        // 主线程拿锁后启动t线程
        synchronized (Tst03BLOCKState.class){
            t.start();
            TimeUnit.SECONDS.sleep(2L);
            System.out.println(t.getState());
        }
    }
}

WAITING状态

  • wait状态必须手动唤醒
java 复制代码
package com.ysf;

import java.util.concurrent.TimeUnit;

public class Tst04WaitState {

    public static void main(String[] args) throws InterruptedException {
        Object obj = new Object();
        Thread t = new Thread(()->{
            synchronized (obj){
                try {
                    // 调用wait方法等待,wait方法一定要手动唤醒
                    obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        
        t.start();
        TimeUnit.SECONDS.sleep(2L);
        System.out.println(t.getState());
    }
}

TIMED_WAITING

  • 调用sleep或join方法
java 复制代码
package com.ysf;

import java.util.concurrent.TimeUnit;

public class Tst05TimedWaiting {

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(()->{
            try {
                // t休眠1秒
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t.start();
        // 主线程休眠0.5秒
        TimeUnit.MILLISECONDS.sleep(500L);
        // 此时t应仍在休眠,因此getState方法应为TIMED_WAITING状态
        System.out.println(t.getState());
    }
}

TERMINATED状态

java 复制代码
package com.ysf;

import java.util.concurrent.TimeUnit;

public class Tst06Terminated {

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(()->{
            try {
                // t休眠0.5秒
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t.start();
        // 主线程休眠1秒
        TimeUnit.MILLISECONDS.sleep(1000L);
        // 此时t应执行结束了,因此getState方法应为TERMINATED状态
        System.out.println(t.getState());
    }
}

线程的常用方法

获取当前线程

java 复制代码
package com.ysf;

public class Tst07CurrentThread {

    public static void main(String[] args) {
        Thread main = Thread.currentThread();
        // 获取并打印当前线程
        // 输出结果:Thread[main,5,main]
        // 线程名,优先级,组名
        System.out.println(main);
    }
}
相关推荐
一颗花生米。14 分钟前
深入理解JavaScript 的原型继承
java·开发语言·javascript·原型模式
问道飞鱼15 分钟前
Java基础-单例模式的实现
java·开发语言·单例模式
ok!ko4 小时前
设计模式之原型模式(通俗易懂--代码辅助理解【Java版】)
java·设计模式·原型模式
2402_857589364 小时前
“衣依”服装销售平台:Spring Boot框架的设计与实现
java·spring boot·后端
吾爱星辰5 小时前
Kotlin 处理字符串和正则表达式(二十一)
java·开发语言·jvm·正则表达式·kotlin
哎呦没5 小时前
大学生就业招聘:Spring Boot系统的架构分析
java·spring boot·后端
编程、小哥哥6 小时前
netty之Netty与SpringBoot整合
java·spring boot·spring
IT学长编程7 小时前
计算机毕业设计 玩具租赁系统的设计与实现 Java实战项目 附源码+文档+视频讲解
java·spring boot·毕业设计·课程设计·毕业论文·计算机毕业设计选题·玩具租赁系统
莹雨潇潇7 小时前
Docker 快速入门(Ubuntu版)
java·前端·docker·容器
杨哥带你写代码7 小时前
足球青训俱乐部管理:Spring Boot技术驱动
java·spring boot·后端