常用方法第一组

  1. setName 设置线程名称,使之与参数name相同
  2. getName 返回该线程的名称
  3. start
  4. run
  5. setPriority 改更线程的优先级
  6. gerPriority 获得线程的优先级
  7. sleep 在指定的毫秒数内让当前正在执行的线程休眠(暂停执行)
  8. interrupt 中断线程
public class Thread_method {
    public static void main(String[] args) throws InterruptedException {
        ThreadDemo1 t1 = new ThreadDemo1();

        //setName 设置线程名称
        t1.setName("内河");
        //setPriority 设置线程的优先级
        t1.setPriority(Thread.MIN_PRIORITY);
        t1.start();

        //主线程打印5 hi,然后中断 子线程的休眠
        for (int i = 0; i <5 ; i++) {
            Thread.sleep(1000);
            System.out.println("hi" +i);
        }

        t1.interrupt();//当执行到这时,就会中断t线程的休眠
        //获得优先级
        System.out.println(t1.getPriority());
    }
}

class ThreadDemo1 extends Thread{

    public void run() {
        while(true) {
            for (int i = 0; i < 100; i++) {
                //Thread.currentThread().getName() 获取当前线程名称
                System.out.println(Thread.currentThread().getName() + " 吃包子" + i);
            }
            try {
                System.out.println(Thread.currentThread().getName() + " 休眠中~~");
                Thread.sleep(20000);
            } catch (InterruptedException e) {
                //当该线程执行到一个interrupt 方法时,就会catch 一个 异常,可以加入自己的业务代码
                // InterruptedException
                System.out.println(Thread.currentThread().getName() + "被 interrrupt了");
            }
        }
    }
}

常用方法第二组

  1. yield: 线程的礼让,让出cpu,让其他线程执行,但礼让时间不确定,所以也不一定礼让成功。
  2. join:线程的插队。查对的线程一旦插队成功,则肯定先执行完插入的线程所有的任务。

join 例子

public class Thread_method2 {
    public static void main(String[] args) throws InterruptedException {
        T2 t2 = new T2();
        t2.start();

        for (int i = 0; i <20 ; i++) {
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName()+" haha "+i);
            if (i==10){
                t2.join();
            }
        }
    }
}

class T2 extends Thread{

    @Override
    public void run() {
        for (int i = 0; i <20 ; i++) {
            try{
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"JoinThread------"+i);
        }
    }
}

用户线程和守护线程

  1. 用户线程:也叫工作线程,当线程的任务执行完或投资方式结束
  2. 守护线程:一般是为工作线程服务的,当所有的用户线程结束,守护线程自动结束