{ System.out.println("스레드 이름="+Thread.currentThread().getName());},threadName);//set 메서드//thread.setName"/> { System.out.println("스레드 이름="+Thread.currentThread().getName());},threadName);//set 메서드//thread.setName">

 >  기사  >  Java  >  Java 스레드에서 일반적으로 사용되는 작업은 무엇입니까?

Java 스레드에서 일반적으로 사용되는 작업은 무엇입니까?

WBOY
WBOY앞으로
2023-04-24 11:55:07856검색

스레드의 일반적인 작업

스레드 이름 설정: setName()

스레드 이름 가져오기: getName()

스레드 고유 ID: getId()

// 自定义线程名称
String threadName = "threadName";
// 构造方法方式
Thread thread = new Thread(() -> {
    System.out.println("线程名=" + Thread.currentThread().getName());
},threadName);
// set方法方式
// thread.setName(threadName);
System.out.println("线程唯一Id=" + thread.getId());

스레드 시작: start()

스레드가 다음과 같은지 여부를 판단합니다. Alive: isAlive( )

// 线程启动
thread.start();
System.out.println("是否为存活线程=" + thread.isAlive());

Thread 메소드: run() /call()

스레드가 시작된 후 호출될 메소드입니다. 스레드가 수행하려는 작업은 실행/호출 메서드에 기록됩니다. 스레드가 시작된 후에는 run()/call()을 호출할 필요가 없습니다. 프로그램이 스레드를 시작하지 않고 직접 실행/호출을 호출하는 경우 다중 스레드 프로그래밍에 속하지 않지만 일반 메소드를 직접 호출하는 것은 현재 스레드에 속합니다.

현재 스레드 객체 가져오기: currentThread()

현재 스레드의 비정적 메서드를 작동하려면 먼저 스레드 객체를 가져와야 합니다.

// 获取当前线程对象
Thread currentThread = Thread.currentThread();
// 对当前线程做一些操作
System.out.println(currentThread.getName());
try {
    // sleep 静态方法则不需要
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
}

스레드 상태 제어(라이프 사이클) 작업에 대해서는 이전 항목을 참조하세요. 기사.

데몬 스레드(백그라운드 스레드)

일반 스레드(사용자 스레드)의 수호자. 데몬 스레드의 임무는 다른 스레드에 서비스를 제공하는 것입니다. 프로세스에 사용자 스레드가 없으면 데몬 스레드는 의미가 없으며 JVM도 종료됩니다. 일반적인 데몬 스레드에는 JVM의 가비지 수집 스레드가 포함되며 운영 체제를 시작하면 다양한 모듈의 데몬 스레드도 시작됩니다.

스레드를 데몬 스레드로 설정: setDaeman()

참고: 이 메서드는 start() 메서드 전에 호출해야 합니다

public static void main(String[] args) {
    Thread thread = new Thread(() -> {
        System.out.println("线程名="+Thread.currentThread().getName());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 这一句不会打印出来,因为main线程(目前唯一的普通线程)等待1秒后已经结束了
        System.out.println("守护线程的状态=" + Thread.currentThread().getState());
    });
    // 守护线程
    thread.setDaemon(true);
    // 线程启动
    thread.start();
    System.out.println("是否为守护线程=" + thread.isDaemon());
}

스레드 직렬화

join() 메서드를 실행하는 스레드는 대기 깨우기 모드에 들어갑니다. 상태(WAITING) , 이 메소드를 호출한 스레드가 종료된 후 대기 중인 깨우기 상태에서 실행 가능 상태(RUNNABLE)로 변경될 때까지. Join() 메소드는 Thread 클래스의 메소드입니다. 기본 메소드는 스레드 대기를 실현하기 위해 wait() 메소드를 사용하는 것입니다. 스레드 isAlive()가 false이면 스레드의 직렬화가 실현됩니다. 한 스레드가 다른 스레드를 호출합니다. 스레드 객체인 Join()은 스레드 직렬화 실행을 구현합니다. 예: 좋은 요리

public class DemoCooking {
    
    public static void main(String[] args) {
        Thread mainThread = Thread.currentThread();
        // 1.买菜
        Thread buyThread = new Thread(new CookingThread(mainThread,"买菜"),"buyThread");
        // 2.洗菜
        Thread washThread = new Thread(new CookingThread(buyThread,"洗菜"),"washThread");
        // 3.切菜
        Thread cutThread = new Thread(new CookingThread(washThread,"切菜"),"cutThread");
        // 4.炒菜
        Thread scrambleThread = new Thread(new CookingThread(cutThread,"炒菜"),"scrambleThread");

        // 不受线程启动顺序的影响
        scrambleThread.start();
        washThread.start();
        cutThread.start();
        buyThread.start();
        
        // main线程先执行完才可以开始:买菜
        System.out.println("开始准备……");
    }

    public static class CookingThread implements Runnable{
        private final Thread thread;
        private final String job;

        public CookingThread(Thread thread, String job){
            this.thread = thread;
            this.job = job;
        }
        @Override
        public void run() {
            String name = Thread.currentThread().getName()+":";
            try {
                thread.join();

                System.out.println(name + job + "开始");
                Thread.sleep(1000);
                System.out.println(name + job + "结束");
                Thread.sleep(1000); // 偷懒下
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

실행 결과: main > buyThread > shambleThread > End

준비 시작...buyThread: 음식 구매 시작

washThread: 설거지 시작

washThread: 설거지 종료
cutThread: 다지기 시작

cutThread: 다지기 종료
scrambleThread: 볶음 시작
scrambleThread: 볶음 종료


실 우선순위

우선순위를 설정하세요 현재 스레드의 스레드 우선순위가 높을수록 스레드가 더 많이 실행될 수 있습니다. Java 스레드의 우선순위는 정수로 표시되며 기본값은 5입니다.

setPriority(int) 메소드: 스레드의 우선순위를 설정합니다.

getPriority 메소드: 스레드의 우선순위를 가져옵니다.

public static void main(String[] args) {

    Thread thread = new Thread(() -> {
        System.out.println("线程1");
    });
    thread.setPriority(10);
    Thread thread1 = new Thread(() -> {
        System.out.println("线程2");
    });
    thread1.setPriority(1);
    thread.start();
    thread1.start();

    System.out.println("线程默认的优先级为=" + Thread.currentThread().getPriority());

}

스레드 중단

interrupt() 메서드를 사용하여 스레드 중단 플래그를 true로 설정하면 스레드가 "차단"될 때 인터럽트 신호가 발생합니다. 스레드가 차단되거나 절전 모드 해제를 기다리고 있거나 시간 초과 대기 상태(Object.wait, Thread.join 및 Thread.sleep)인 경우 인터럽트 예외(InterruptedException)를 수신하고 상태를 조기에 종료합니다. 반면에 스레드가 "RUNNABLE" 상태에 있으면 인터럽트 플래그는 아무런 효과가 없습니다.

사례 1: 스레드 중단이 유효합니다

public static void main(String[] args) {
    Thread thread = new Thread(() -> {
        System.out.println("线程1");
        try {
            // 闹钟1分钟后响
            Thread.sleep(60000);
            System.out.println("闹钟响了");
        } catch (InterruptedException e) {
            // 提前退出超时等待状态
            System.out.println("发生异常,提前醒了,闹钟没响手动关了");
        }

        System.out.println("继续执行该线程的后续程序……");

    });
    thread.setPriority(1);
    thread.start();
    thread.interrupt();
    System.out.println("main线程将thread 终端状态设置为 "+thread.isInterrupted());
}

실행 결과:

메인 스레드가 스레드 터미널 상태를 true로 설정합니다.

스레드 1

예외가 발생했습니다. 일찍 일어났고, 알람이 울리지 않았으며, 수동으로 껐습니다.

스레드 프로그램의 후속 실행을 계속합니다...

사례 2: 스레드 중단이 유효하지 않습니다

public static void main(String[] args) {
    Thread thread1 = new Thread(() -> {
        System.out.println("线程" + Thread.currentThread().getName());
        while (true) {
            System.out.print(Thread.currentThread().getState() + "\t");
        }
    });
    thread1.start();
    thread1.interrupt();
}

실행 결과: 스레드가 계속 RUNNABLE 상태를 인쇄합니다.

위 내용은 Java 스레드에서 일반적으로 사용되는 작업은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제