Thread 类的基本用法(包括线程创建,线程中断,线程等待,获取线程实例与线程状态)

一.线程创建

这里介绍五种创建线程的基本方式:

1.创建子类,继承thread,重写run

//创建子类,继承thread,重写run,通过start启动线程
class MyThread extends Thread{//具名类
    @Override
    public void run() {
        while(true){
            System.out.println("子线程");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }//不能直接在run后throws,只能try catch
        }
    }
}

public class demo1 {
    public static void main(String[] args) throws InterruptedException {
        MyThread t = new MyThread();
        t.start();//会创建一个新的线程,并调用run方法,新线程和主线程交替执行
        // t.run();//不会创建新的线程,而是在主线程中调用run方法,主线程会等待run方法执行完毕,才会继续执行
        while(true){
            System.out.println("主线程");
            Thread.sleep(1000);
        }
    }
}

2.创建子类,实现runnable接口,重写run,搭配thread的实例

//创建子类,实现runnable接口,重写run,搭配thread的实例,进行start


class runnable implements Runnable{
    @Override
    public void run() {
        while(true){
            System.out.println("子线程");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }//不能直接在run后throws,只能try catch
        }
    }
}


public class demo2 {
public static void main(String[] args) {
    Runnable r = new runnable();//使用runnable接口来描述线程的任务
    Thread t = new Thread(r);//创建线程对象,并将runnable对象作为参数传递
    t.start();//启动线程,会调用runnable对象的run方法
    while(true){
            System.out.println("主线程");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
}
}

3.创建子类,继承thread,重写run,但通过匿名内部类进行了简写

//创建子类,继承thread,重写run,通过start启动线程,但通过匿名内部类进行了简写

public class demo3 {
    /**
     * @param args
     */
    public static void main(String[] args) {
        Thread t = new Thread(){//匿名内部类
        @Override
        public void run() {
            while(true){
                System.out.println("子线程");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    };
    t.start();
    while(true){
        System.out.println("主线程");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
}

4.创建子类,实现runnable接口,重写run,搭配thread的实例,但通过匿名内部类进行了简写

//创建子类,实现runnable接口,重写run,搭配thread的实例,进行start,但通过匿名内部类进行了简写

public class demo4 {
public static void main(String[] args) {
    // 使用Runnable接口和匿名内部类创建线程
    Runnable r = new Runnable() {

        @Override
        public void run() {
            while(true) {
                System.out.println("子线程");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    Thread t = new Thread(r);
    t.start();
    
    // 主线程的循环输出
    while(true) {
        System.out.println("主线程");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
}

5.基于lambda表达式创建线程

//基于lambda表达式创建线程,lambda表达式,本质上是一个匿名函数,可以作为参数传递,也可以作为返回值返回
public class demo5 {
public static void main(String[] args) {
    //基于lambda表达式创建线程
    //lambda表达式,本质上是一个匿名函数
    Runnable r = () -> {
         while(true) {
            System.out.println("子线程");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
        //或者Thread t = new Thread(() -> {
            // while(true) {
            //     System.out.println("子线程");
            //     try {
            //         Thread.sleep(1000);
            //     } catch (InterruptedException e) {
            //         e.printStackTrace();
            //     }
            // }
        //}, "子线程");//可起名字

        //t.start();
    Thread t = new Thread(r);
    t.start();
    while(true) {
        System.out.println("主线程");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
}

其中第五种基于lambda表达式创建线程最简洁也最常用

二.线程中断


//中断线程,sleep提前唤醒
public class Thread_interrupted {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(()->{
            while(!Thread.currentThread().isInterrupted()){
                System.out.println("hello Thread");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    //这里可以让程序员自行选择如何操作,跳出(break结束线程),或者do something或者稍等一会再操作
                }
            }
        });
        t.start();
        Thread.sleep(2000);
        t.interrupt();//唤醒了sleep
        System.out.println("hello main");
        //如果没有进行sleep等阻塞操作,t的isinterrupted()标志位会置为true,然后正常结束循环,
        // 如果有阻塞操作,还是一样,但是,如果sleep被提前唤醒了,会同时把isinterrupted()重置为false,所以会陷入条件死循环,
        // 为避免此情况,就需要考虑手动结束线程了
    }
}

三.线程等待


//join线程等待:由于线程的执行先后顺序并不一定,通过join可以让某一线程等待另一个线程执行结束后再执行
//额外的有join(long millis)表示该线程最多等待多少毫米后执行
public class Thread_Join {
//    public static void main(String[] args) throws InterruptedException {
//        Thread t = new Thread(()->{
//            for(int i = 0;i< 5;i++) {
//                System.out.println("hello thread");
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//
//        });
//        t.start();
//        System.out.println("等待t线程结束之前");
//        t.join();//main线程必须等t线程执行完后才会执行
//        System.out.println("等待t线程结束之后");
//        System.out.println("hello main");
//
//
//
//    }
//    当然也可以让t线程等待main线程
public static void main(String[] args) throws InterruptedException {
    Thread main_thread = Thread.currentThread();//获取main线程
    Thread t = new Thread(()->{
        System.out.println("等待main线程结束之前");
        try {
            main_thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("等待main线程结束之后");

    });
    t.start();
    for(int i = 0;i<4;i++){
        System.out.println("hello main");
        Thread.sleep(1000);
    }
}
}

四.获取线程实例

public class Current_thread {
    public static void main(String[] args) {
        // 获取当前线程(主线程)
        Thread mainThread = Thread.currentThread();
        System.out.println("主线程名称:" + mainThread.getName());
        System.out.println("主线程ID:" + mainThread.getId());
        
        // 创建并启动子线程
        Thread thread = new Thread(() -> {
            // 获取当前执行线程(子线程)
            Thread current = Thread.currentThread();
            System.out.println("子线程名称:" + current.getName());
            System.out.println("子线程ID:" + current.getId());
        }, "MyThread");
        
        thread.start();
        
        // 等待子线程执行完毕
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

//常用线程信息方法:
//String getName():获取线程名称
//long getId():获取线程唯一 ID
//int getPriority():获取线程优先级
//Thread.State getState():获取线程状态
//boolean isAlive():判断线程是否存活

五.线程状态


//Thread 类定义了 6 种线程状态,通过getState()方法获取:
// NEW:新建状态,尚未启动
// RUNNABLE:可运行状态,正在 JVM 中执行或等待 CPU 资源
// BLOCKED:阻塞状态,等待获取锁
// WAITING:等待状态,无限期等待其他线程通知
// TIMED_WAITING:计时等待状态,在指定时间内等待
// TERMINATED:终止状态,已完成执行
public class Thread_State {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println("创建后状态:" + thread.getState()); // NEW

        thread.start();
        System.out.println("启动后状态:" + thread.getState()); // RUNNABLE或TIMED_WAITING

        try {
            Thread.sleep(200);
            System.out.println("运行中状态:" + thread.getState()); // TIMED_WAITING
            thread.join();
            System.out.println("结束后状态:" + thread.getState()); // TERMINATED
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值