线程

线程

创建线程

创建线程的第一种方式:

  • 1.定义Thread类的子类,并重写该类的run()方法,该run()方法的方法体就代表了线程需要完成的任务,因此把run()方法称为线程执行体。

  • 2.创建Thread子类的实例,即创建了线程对象

  • 3.调用线程对象的start()方法来启动该线程

  • 注意:

  • 1.加入了多线程之后,JVM内存:方法区,堆,主栈(main方法里面的代码),分支栈(自定义线程类中的代码)

  • 2.运行结果有先有后,有多有少,原因:Java中的线程是抢占式调度,谁先抢到CPU时间片,谁先执行

public class ThreadTest00 {
   public static void main(String[] args) {//主线程
       MyThread mt = new MyThread();
       mt.start();
       for (int i = 0; i < 50; i++) {
           System.out.println("main:"+i);
       }
   }
}
//线程类
class MyThread extends Thread{//分支线程
   @Override
   public void run() {
       for (int i = 0; i < 50; i++) {
           System.out.println("MyThread:"+i);
       }
   }
}

线程创建的第二种方式:

实现Runnable接口————实际工作中推荐此方式创建线程
定义一个线程类,实现Runnable接口
实现Run方法
创建对象:public Thread(Runnable target)
调用start方法启动线程

输出结果:有先有后,有多有少,因为Java是抢占式调度,多个线程抢占CPU时间片是随机的,谁抢到谁执行

好处:
1.避免了单继承的局限性
一个类只能继承一个类,线程类继承了Thread类就不能再继承其他类,
实现Runnable接口,还有继承其他类和实现其他接口的功能。
2.增强了程序的扩展性,降低了程序的耦合性(解耦):
实现了runnable接口的方式把设置线程任务和开启线程进行了分离(解耦)

public class ThreadTest01 {
    public static void main(String[] args) {
        MyThread01 mt = new MyThread01();
        Thread t = new Thread(mt);
        /*
        注:当调用start(),它会先告诉JVM开辟分支栈内存空间,
        系统会自动调用重写后的run方法,无需程序员调用!!!
         */
        t.start();
        for (int i = 0; i < 200; i++) {
            System.out.println("main---"+i);
        }
    }
}
//定义线程类
class MyThread01 implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("Thread---"+i);
        }
    }
}

线程创建的第三种方式:匿名内部类

/*
线程创建的第三种方式:匿名内部类
 */
public class ThreadTest02 {
    public static void main(String[] args) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    System.out.println("run---"+i);
                }
            }
        });
        t.start();
    }
}

线程中常用方法:

线程中常用方法1:——获取当前线程对象,赋名,取名

/*
线程中常用方法1:——获取当前线程对象,赋名,取名
public static Thread currentThread()返回对当前正在执行的线程对象的引用。
public final void setName(String name)将此线程的名称更改为等于参数name 。
public final String getName()返回此线程的名称。
 */
public class ThreadTest03 {
    public static void main(String[] args) {
        Thread t = new Thread(new MyThread1());
        t.setName("t");
        t.start();//t
        Thread t1 = new Thread(new MyThread1());
        t1.setName("t1");
        t1.start();//t1
    }
}
class MyThread1 extends Thread{
    @Override
    public void run() {
        Thread t = Thread.currentThread();
        System.out.println(t.getName());//Thread-1

    }
}

线程中常用方法2:——线程的优先级(1-10)

/*
线程中常用方法2:——线程的优先级(1-10)
最高:10 最低:1 默认:5
public static final int MAX_PRIORITY线程可以拥有的最大优先级。
public static final int MIN_PRIORITY线程可以拥有的最小优先级。
public static final int NORM_PRIORITY分配给线程的默认优先级。
public final void setPriority(int newPriority)更改此线程的优先级。
public final int getPriority()返回此线程的优先级。
 */
public class ThreadTest04 {
    public static void main(String[] args) {
        System.out.println(Thread.MAX_PRIORITY);//10
        System.out.println(Thread.MIN_PRIORITY);//1
        System.out.println(Thread.NORM_PRIORITY);//5
        Thread t1 = new Thread(new MyThread2());
        t1.setName("t1");
        Thread t2 = new Thread(new MyThread2());
        t2.setName("t2");
        System.out.println(t1.getPriority());
        System.out.println(t2.getPriority());
        t1.setPriority(1);
        t2.setPriority(10);
        t1.start();
        t2.start();
    }
}
class MyThread2 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            System.out.println(Thread.currentThread());
        }
    }
}

线程中常用方3:——线程休眠

/*
线程中常用方3:——线程休眠:
public static void sleep(long millis) throws InterruptedException
1.静态方法
2.抛出异常
3.参数:毫秒值
4.作用:让当前线程进入休眠,放弃占有的CPU时间片,让给其他线程使用
5.经常使用场景:间隔一定时间执行一段代码
 */
public class ThreadTest05 {
    public static void main(String[] args) throws InterruptedException {
        //5秒后执行以下代码
        Thread.sleep(5000);
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName()+"---"+i);
        }
    }
}

线程中常用方4:——终止线程休眠:

/*
线程中常用方4:——终止线程休眠:
睡眠太久,中途醒来的方法:
public void interrupt()中断这个线程的休眠。
 */
public class ThreadTest06 {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(new MyThread3());
        t.setName("t");
        t.start();
        //希望5秒后,线程醒来
        Thread.sleep(1000*5);
        //中断线程
        t.interrupt();
    }
}
class MyThread3 implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"----begin");
        try {
            Thread.sleep(365*24*60*60*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"----end");
    }
}

线程中常用方5:-------合理终止一个线程

/*
线程中常用方5:——
怎么合理终止一个线程?不建议使用API中stop方法
 */
public class ThreadTest07 {
    public static void main(String[] args) throws InterruptedException {
        MyThread04 mt = new MyThread04();
            Thread t = new Thread(mt);
             t.setName("t");
             t.start();
             //5秒后中止线程
        Thread.sleep(5000);
        mt.flag = false;
    }
}

class MyThread04 implements Runnable{
    //写布尔标记
    boolean flag = true;
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            if(flag){
                System.out.println(Thread.currentThread().getName()+i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else{
                //终止
                return;
            }
        }
    }
}
posted @ 2021-08-22 22:32  勇敢的勇  阅读(72)  评论(0)    收藏  举报