栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA ——线程概念(线程的生命周期及使用)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA ——线程概念(线程的生命周期及使用)

线程的生命周期

首先让我们了解一下java中线程的周期

分为几种状态:

  • 新建 NEW
  • 运行 RUNNING
  • 阻塞 BLOCKING
  • 死亡 DEAD
线程常用方法
方法介绍
start()启动
stop()停止(禁用,可能导致线程死锁等问题),停止线程可以让run执行结束
String getName()获得线程的名字
setName(String)设置线程名字
sleep(long)进入睡眠,毫秒
setPriority(int)设置线程的优先级(1~10从低到高)越高抢CPU几率更高
setDaemon(boolean)设置为后台线程 true ,后台线程是为其它线程服务的,如果没有其它线程存在,就自动死亡;使用案例:GC就是一种后台线程
join()在A线程中调用了B线程的join()方法时,表示只有当B线程执行完毕时,A线程才能继续执行。
线程的实现方式
  1. 继承Thread类
  2. 实现Runnable接口
  3. 实现Callable接口
  4. 使用线程池

1.继承Thread类

class MyThread extends Thread{

    
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() +"执行了" + i);
        }
    }
}

public class ThreadDemo {

    public static void main(String[] args) {
        //创建线程对象
        MyThread myThread = new MyThread();
        //启动线程
        myThread.start();
        //主线程执行
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() +"执行了" + i);
        }
    }
}

2.实现Runnable接口


class MyThread implements Runnable {
    public void run(){
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + "线程" + i);
        }
    }
}

public class ThreadDemo {
    public static void main(String[] args) {
        //lambda表达式
        Thread thread1 = new Thread(()->{
            for (int i = 0; i < 100; i++) {
                System.out.println(Thread.currentThread().getName() + "线程" + i);
            }
        });

        //匿名内部类
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    System.out.println(Thread.currentThread().getName() + "线程" + i);
                }
            }
        });


        thread.start();
        thread1.start();
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + "线程" + i);
        }
    }
}

3.实现Callable接口 注意:调用get方法得到返回结果


class MyCallable implements Callable {
    @Override
    public Long call() throws Exception {
        long sum = 0;
        for (long i = 0; i < 10000000; i++) {
            sum += i;
        }
        System.out.println(sum);
        return sum;
    }

}

public class CallableDemo {
    public static void main(String[] args) {
        //普通方式
        FutureTask futureTask = new FutureTask<>(new MyCallable());

        //lambda表达式方式
        FutureTask futureTask1 = new FutureTask(() ->{
            long sum = 0;
            for (long i = 0; i < 10000000; i++) {
                sum += i;
            }
            System.out.println(sum);
            return sum;
        });
        new Thread(futureTask).start();
        new Thread(futureTask1).start();
        System.out.println("等待结束");
    }
}

一些关于线程的小练习

public class Demo1 {
    public static void main(String[] args) {
        //1~100内偶数
        Thread t1 = new Thread(() -> {
            for (int i = 1; i < 100; i++) {
                if (i % 2 == 0) {
                    System.out.println("线程1---偶数:" + i);
                }
            }
        });

        //1~100内奇数
        Thread t2 = new Thread(()->{
            for (int i = 1; i < 100; i++) {
                if (i % 2 != 0){
                    System.out.println("线程2---奇数:" + i);
                }
            }
        });

        t1.setPriority(8);
        t2.setPriority(3);

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


public class Demo2 {
    public static void getFiles(String p) {
        StringBuilder path = new StringBuilder(p).append("/");
        File file = new File(path.toString());
        File[] tempList = file.listFiles();
        //遍历该目录下所有东西
        for (int i = 0; i < tempList.length; i++) {
            //如果是文件,就读取并打印
            if (tempList[i].isFile()) {
                print(new File(path + tempList[i].getName()));
                System.out.println(tempList[i].getName());
            }
        }
    }

    //写一个IO流读取文件的方法
    public static void print(File file){
        //要读取的目标文件
        FileReader fr = null;
        try {
            fr = new FileReader(file);
            char[] chars = new char[1024];
            int len;
            while ((len = fr.read(chars)) != -1){
                String s = new String(chars, 0, len);
                System.out.println(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> getFiles("D:\111\java4\src") );
        t1.start();
    }
}


public class Demo3 {
    public static void main(String[] args) {
        for (int i = 1; i < 89; i++) {
            System.out.println("播放第" + i + "集");
            if (i == 10){
                Thread thread = new Thread(() -> System.out.println("快递到了,去拿快递"));
                thread.start();
                try {
                    //注意:join之前,一定要将线程处于准备状态start
                    thread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}



public class Demo4 {
    public static void main(String[] args) {
        int destination = 1000;
        new Thread(() -> {
            for (int i = destination; i != 0; i-=5) {
                if(i % 20 == 0 && i != destination){
                    try {
                        System.out.println("兔子累了,距离终点" + i);
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            System.out.println("兔子获胜");
            System.exit(0);
        }).start();

        new Thread(() -> {
            for (int i = destination; i != 0; i-=1) {
                if(i % 100 == 0 && i != destination){
                    try {
                        System.out.println("乌龟累了,距离终点" + i);
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            System.out.println("乌龟获胜");
            System.exit(0);
        }).start();
    }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/644752.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号