多线程常用方法

发布时间 2023-12-14 22:01:46作者: 防守三巨臀

public class ThreadDemo {
  public static void main(String[] args) throws InterruptedException {
    /*
    String getName() 返回此线程的名称
    void setName(String name) 设置线程的名字(构造方法也可以设置名字)
    细节:
    1、如果我们没有给线程设置名字,线程也是有默认的名字的
    格式:Thread-X(X序号,从0开始的)
    2、如果我们要给线程设置名字,可以用set方法进行设置,也可以构造方法设置

    static Thread currentThread() 获取当前线程的对象
    细节:
    当JVM虚拟机启动之后,会自动的启动多条线程
    其中有一条线程就叫做main线程
    他的作用就是去调用main方法,并执行里面的代码
    在以前,我们写的所有的代码,其实都是运行在main线程当中

    static void sleep(long time) 让线程休眠指定的时间,单位为毫秒
    细节:
    1、哪条线程执行到这个方法,那么哪条线程就会在这里停留对应的时间
    2、方法的参数:就表示睡眠的时间,单位毫秒
      1 秒= 1000毫秒
    3、当时间到了之后,线程会自动的醒来,继续执行下面的其他代码
    */

    //1.创建线程的对象
    MyThread t1 = new MyThread("飞机");
    MyThread t2 = new MyThread("坦克");

    //2.开启线程

    t1.start();
    t2.start();

    //哪条线程执行到这个方法,此时获取的就是哪条线程的对象
    /* Thread t = Thread.currentThread();
    String name = t.getName();
    System.out.println(name);//main*/

    /*System.out.println("11111111111");
    Thread.sleep(5000);
    System.out.println("22222222222");*/

  }
}

 

public class ThreadDemo {
  public static void main(String[] args){
    /*
    setPriority(int newPriority) 设置线程的优先级
    final int getPriority() 获取线程的优先级
    */

    //创建线程要执行的参数对象
    MyRunnable mr = new MyRunnable();
    //创建线程对象
    Thread t1 = new Thread(mr,"飞机");
    Thread t2 = new Thread(mr,"坦克");

    t1.setPriority(1);
    t2.setPriority(10);

    t1.start();
    t2.start();
  }
}

 

public class ThreadDemo {
  public static void main(String[] args) {
  /*
  final void setDaemon(boolean on) 设置为守护线程
  细节:
  当其他的非守护线程执行完毕之后,守护线程会陆续结束
  通俗易懂:
  当女神线程结束了,那么备胎也没有存在的必要了
  */

 

    MyThread1 t1 = new MyThread1();
    MyThread2 t2 = new MyThread2();

    t1.setName("女神");
    t2.setName("备胎");

    //把第二个线程设置为守护线程(备胎线程)
    t2.setDaemon(true);

    t1.start();
    t2.start();

  }
}

 

public class ThreadDemo {
  public static void main(String[] args) {
  /*
  public static void yield() 出让线程/礼让线程

  */

  MyThread t1 = new MyThread();
  MyThread t2 = new MyThread();

  t1.setName("飞机");
  t2.setName("坦克");

  t1.start();
  t2.start();

}
}

public class MyThread extends Thread{

  @Override
  public void run() {//"飞机" "坦克"
  for (int i = 1; i <= 100; i++) {

  System.out.println(getName() + "@" + i);
  //表示出让当前CPU的执行权 比如飞机线程走到这个方法让出线程 但是还有可能再抢到
  Thread.yield();
  }
  }
}

public class ThreadDemo {
  public static void main(String[] args) throws InterruptedException {
  /*
  public final void join() 插入线程/插队线程
  */

   MyThread t = new MyThread();

  t.setName("土豆");
  t.start();

  //表示把t这个线程,插入到当前线程之前。
  //t:土豆
  //当前线程: main线程
  t.join();

  //执行在main线程当中的
  for (int i = 0; i < 10; i++) {
  System.out.println("main线程" + i);
  }

}
}