JavaEE初阶----Thread 类的基本用法
1.线程的创建
2.线程中断
李四一旦进到工作状态,他就会按照行动指南上的步骤去进行工作,不完成是不会结束的。但有时我们需要增加一些机制,例如老板突然来电话了,说转账的对方是个骗子,需要赶紧停止转账,那张三该如何通知李四停止呢?这就涉及到我们的停止线程的方式了。
目前常见的有以下两种方式:
- 通过共享的标记来进行沟通
 - 调用 interrupt() 方法来通知
 
下面我们主要讲讲常用的interrupt方法:
private static void test2() {
          
   
    Thread thread = new Thread(() -> {
          
   
        while (true) {
          
   
            Thread.yield();
            // 响应中断
            if (Thread.currentThread().isInterrupted()) {
          
   
                System.out.println("线程被中断,程序退出。");
                return;
            }
        }
    });
    thread.start();
    thread.interrupt();
} 
3.线程等待
有时,我们需要等待一个线程完成它的工作后,才能进行自己的下一步工作。例如,张三只有等李四转 账成功,才决定是否存钱,这时我们需要一个方法明确等待线程的结束。
public class ThreadDemo {
          
   
    public static void main(String[] args) throws InterruptedException {
          
   
        Runnable target = () -> {
          
   
            for (int i = 0; i < 10; i++) {
          
   
                try {
          
   
                    System.out.println(Thread.currentThread().getName() 
                                       + ": 我还在工作!");
                    Thread.sleep(1000);
               } catch (InterruptedException e) {
          
   
                    e.printStackTrace();
               }
           }
            System.out.println(Thread.currentThread().getName() + ": 我结束了!");
       };
        Thread thread1 = new Thread(target, "李四");
        Thread thread2 = new Thread(target, "王五");
        System.out.println("先让李四开始工作");
        thread1.start();
        thread1.join();
        System.out.println("李四工作结束了,让王五开始工作");
        thread2.start();
        thread2.join();
        System.out.println("王五工作结束了");
   }
} 
4.线程休眠
这个就是老顾客了,sleep就完事
public class ThreadDemo {
          
   
    public static void main(String[] args) throws InterruptedException {
          
   
        System.out.println(System.currentTimeMillis());
        Thread.sleep(3 * 1000);
        System.out.println(System.currentTimeMillis());
   }
} 
5.获取线程实例
public class test {
          
   
    public static void main(String[] args) {
          
   
    System.out.println( Thread.currentThread().getName());
    }
}
				       
			          上一篇:
			            Java基础知识总结(2021版) 
			          
			          下一篇:
			            在校学生该怎么进互联网大厂做后端开发? 
			          
			        