Java线程常用方法

线程常用方法

  1. Thread.currentThread():获取当前线程信息

    public static void getCurrentThread() {
        Thread currentThread = Thread.currentThread();
        System.out.println(currentThread);
        //return "Thread[" + getName() + "," + getPriority() + "," + group.getName() + "]";
        //Thread[main,5,main]
    }
    
  2. thread.setName("threadName"):设置线程名称(当出现异常时方便追溯到问题线程)

    public static void setThreadName() {
        Thread thread = new Thread(() -> {
            System.out.println(Thread.currentThread().getName()); //默认:Thread-0,设置名称后:模块-功能-计数器
        });
        thread.setName("模块-功能-计数器");
        thread.start();
    }
    
  3. thread.setPriority(0~10):线程的优先级(取值范围1~10数值越高优先级越高,默认5

    public static void setPriority() {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("t1:" + i);
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("t2:" + i);
            }
        });
        t2.start();
        t1.start();
        t1.setPriority(10); //虽然t2先执行,但t1的优先级最高,所以t1会由cpu优先调度
        t2.setPriority(1);
    }
    
  4. Thread.yield():线程的让步(从运行状态到就绪状态)

    public static void executeYield() {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                if (i == 50) {
                    Thread.yield(); //当t1的i循环到5让t1让出cpu调度(让出后可能cpu马上又分配给了t1)
                }
                System.out.println("t1:" + i);
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                System.out.println("t2:" + i);
            }
        });
        t1.start();
        t2.start();
    }
    
  5. Thread.sleep(time):线程的休眠

    public static void executeSleep() throws InterruptedException {
        System.out.println(System.currentTimeMillis());
        Thread.sleep(1000L);
        System.out.println(System.currentTimeMillis());
    }
    
  6. thread.join():线程的抢占

    public static void executeJoin() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("t1:" + i);
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("t2:" + i);
            }
        });
        t1.start();
        t2.start();
        for (int i = 0; i < 10; i++) {
            System.out.println("main");
            if (i == 1) {
                t1.join(2000);
            }
        }
    }
    
  7. thread.setDaemon(true):设置守护线程

    public static void setDaemon() {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("t1:" + i);
            }
        });
        t1.setDaemon(true); //设置t1为守护线程,主线程结束t1不管有没有执行完毕也随之结束
        t1.start();
    }
    
  8. 线程的等待和唤醒

    public static void executeWaitAndNotify() throws InterruptedException {
        Thread t1 = new Thread(ThreadMethod::sync, "t1");
        Thread t2 = new Thread(ThreadMethod::sync, "t2");
        t1.start();
        t2.start();
        Thread.sleep(12000);
        synchronized (ThreadMethod.class) {
            ThreadMethod.class.notifyAll();
        }
    }
    
    private static synchronized void sync() {
        try {
            for (int i = 0; i < 10; i++) {
                if (i == 5) {
                    ThreadMethod.class.wait();
                }
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName());
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    

    可以让获取synchronized锁资源的线程通过wait()进入到锁的等待池,并且会释放锁资源

    可以让获取synchronized锁资源的线程,通过notify()notifyAll(),将等待池中的线程唤醒,添加到锁池中

    notify()随机的唤醒等待池中的一个线程到锁池

    notifyAll()将等待池中的全部线程都唤醒,并且添加到锁池

    • 等待池:WAITING
    • 锁池:BLOCKED

    在调用wait()notify()以及notifyAll()时,必须在synchronized修饰的代码快或者方法内部才可以,因为要操作基于某个对象的锁的信息维护

  9. 线程的结束方式:线程结束方式很多,最常用的就是让线程的run方法结束,无论是return结束,还是抛出异常结束,都可以

    1. 强制线程结束,无论你在干嘛,不推荐使用,但是他确实可以把线程干掉(不建议)

      public static void executeStop() throws InterruptedException {
          Thread thread = new Thread(() -> {
              try {
                  Thread.sleep(5000);
              } catch (InterruptedException e) {
                  throw new RuntimeException(e);
              }
          });
          thread.start();
          System.out.println(thread.getState()); //RUNNABLE
          thread.stop();
          Thread.sleep(500); //stop()可能存在延迟,需要小小的睡一会儿方可看到结果
          System.out.println(thread.getState()); //TERMINATED
      }
      
    2. 使用共享变量(用的不多):这种方式用的也不多,有的线程可能会通过死循环来保证一直运行,我们可以通过修改共享变量破坏死循环,让线程推出循环,结束run方法

      static volatile boolean flag = true; //共享变量需要使用volatile修饰,否则共享不生效
      public static void executeVolatile() throws InterruptedException {
          Thread thread = new Thread(() -> {
              while (flag) {
                  //do something
              }
              System.out.println("任务结束");
          });
          thread.start();
          Thread.sleep(500);
          flag = false;
      }
      
    3. interrupt:通过打断WAITING或者TIMED_WAITING状态的线程,从而抛出异常自行处理,这种停止线程方式是最常用的一种,在框架和JUC中也是最常见的

      public static void executeInterrupt() throws InterruptedException {
          //线程默认情况下, interrupt标记位:false
          System.out.println(Thread.currentThread().isInterrupted());
          //执行interrupt之后,再次查看打断信息
          Thread.currentThread().interrupt();
          //interrupt标记位:true
          System.out.println(Thread.currentThread().isInterrupted());
          //返回当前线程,并归位为false interrupt标记位:true
          System.out.println(Thread.interrupted());
          //已经归位了
          System.out.println(Thread.interrupted());
      
          Thread thread = new Thread(() -> {
              while (true) {
                  try {
                      Thread.sleep(1000);
                  } catch (InterruptedException e) {
                      System.out.println("基于打断形式结束当前线程");
                      return;
                  }
              }
          });
          thread.start();
          Thread.sleep(500);
          thread.interrupt(); //无法处理BLOCKED
      }
      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中多线程常用方法有以下几种: 1. 继承Thread类:创建一个继承自Thread类的子类,并重写run()方法,在run()方法中定义线程要执行的任务。然后通过创建子类的对象,调用start()方法启动线程。 2. 实现Runnable接口:创建一个实现了Runnable接口的类,并实现其run()方法,在run()方法中定义线程要执行的任务。然后通过创建该类的对象,将其作为参数传递给Thread类的构造方法,再调用start()方法启动线程。 3. 使用Callable和Future:Callable接口是一种带有返回值的线程,通过实现Callable接口并实现其call()方法来定义线程要执行的任务。然后使用ExecutorService的submit()方法提交Callable任务,并返回一个Future对象,通过Future对象可以获取线程执行的结果。 4. 使用线程池:通过Executor框架提供的线程池来管理线程的创建和执行。可以使用Executors类提供的静态方法创建不同类型的线程池,然后将任务提交给线程池执行。 5. 使用synchronized关键字:通过在方法或代码块前加上synchronized关键字来实现线程同步,保证多个线程对共享资源的访问是互斥的。 6. 使用Lock接口:Lock接口提供了比synchronized更灵活和强大的线程同步机制。通过Lock接口的lock()和unlock()方法来实现对共享资源的加锁和解锁。 7. 使用wait()、notify()和notifyAll()方法:通过Object类提供的wait()、notify()和notifyAll()方法来实现线程间的通信和协作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值