重温java知识(三十七、多线程编程之四:多线程常用操作方法)

1、线程的命名和取得的例子:

package com.mydemo;

public class ThreadDemo {

    public static void main(String[] args) {

        MyThread mt = new MyThread();

        new Thread(mt, "线程A").start();      // 设置了线程的名字
        new Thread(mt).start();               // 未设置线程名字
        new Thread(mt, "线程B").start();      // 设置了线程的名字

    }
}


class MyThread implements Runnable {

    @Override
    public void run() {
        // 获取当前线程名称------线程自动命名
        String threadAutoName = Thread.currentThread().getName();
        System.out.println(threadAutoName);
    }
}

运行结果:
线程A
线程B
Thread-0

2、子线程的例子:

package com.mydemo;

public class ThreadDemo {

    public static void main(String[] args) {

        MyThread mt = new MyThread();

        // 子线程
        new Thread(mt, "线程A").start();      // 设置了线程的名字
        new Thread(mt).start();                      // 未设置线程名字
        new Thread(mt, "线程B").start();      // 设置了线程的名字

        // 主线程,mt.run()执行的结果
        mt.run();

    }
}


class MyThread implements Runnable {

    @Override
    public void run() {
        // 获取当前线程名称
        String threadAutoName = Thread.currentThread().getName();
        System.out.println(threadAutoName);
    }
}

运行结果:
main
Thread-0
线程B
线程A

3、子线程处理复杂逻辑的例子:

package com.mydemo;

public class ThreadDemo {

    public static void main(String[] args) {

        // 主线程执行
        System.out.println("1、执行操作任务一*********");

        // 子线程执行
        new Thread(
                () -> {
                    int temp = 0;
                    //
                    System.out.println("子线程开始执行任务了*********");
                    // 模拟耗时操作
                    for (int i = 0; i < Integer.MAX_VALUE; i++) {
                        temp += i;
                    }
                }
        ).start();

        // 主线程执行
        System.out.println("2、执行操作任务一*********");
        System.out.println("N、执行操作任务一*********");
    }
}

运行结果:
1、执行操作任务一*********
2、执行操作任务一*********
N、执行操作任务一*********
子线程开始执行任务了*********

4、线程休眠的例子:

package com.mydemo;

public class ThreadDemo {

    public static void main(String[] args) {

        // Runnable接口实例
        Runnable runnable = () -> {
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "、 i = " + i);
                try {
                    // 暂缓1秒(1000毫秒)执行
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // 强制性异常处理
                    e.printStackTrace();
                }
            }
        };

        for (int i = 0; i < 5; i++) {
            // 启动线程
            new Thread(runnable, "线程对象-" + i).start();
        }
    }
}

5、线程中断的例子【线程的中断是被动完成的,每当被中断执行后就会产生“InterruptedException”异常】:

package com.mydemo;

public class ThreadDemo {

    public static void main(String[] args) throws Exception {

        Thread thread = new Thread(
                () -> {
                    System.out.println("【before】太累了,要睡觉了");
                    try {
                        // 休息10秒吧
                        Thread.sleep(100000);
                        System.out.println("【finish】睡醒了,继续搬砖~");
                    } catch (InterruptedException e) {
                        System.out.println("【Exception】美梦被打断了,坑~~");
                        e.printStackTrace();
                    }
                }
        );

        thread.start();                 // 线程启动
        Thread.sleep(1000);       // 保证子线程先运行个1秒

        // 判断线程是否中断
        if (!thread.isInterrupted()) {
            System.out.println("【Interrupted】一个傻子把我吵醒了");
            thread.interrupt();     // 中断执行
        }
    }
}

运行结果:

6、线程强制执行的例子【待其执行完毕后其他线程再继续执行】:

package com.mydemo;

public class ThreadDemo {

    public static void main(String[] args) throws Exception {

        // 获得主线程
        Thread mainThread = new Thread();
        
        Thread thread = new Thread(
                () -> {
                    for (int i = 0; i < 100; i++) {
                        if (i == 3) {
                            try {
                                // 设置强制执行条件
                                mainThread.join();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                            try {
                                // 延缓执行
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                            System.out.println(Thread.currentThread().getName() + "i = " + i);
                        }
                    }
                }, "嘻嘻线程"
        );

        thread.start();                 // 主线程

        for (int i = 0; i < 100; i++) {
            Thread.sleep(100);
            System.out.println("【强制执行的主线程就是不一样,跟秀才一样】i = " + i);
        }
    }
}

7、线程礼让的例子【将当前的调度让给其他线程执行,自己再等待下次调度再执行】:

package com.mydemo;

public class ThreadDemo {

    public static void main(String[] args) throws Exception {

        Thread thread = new Thread(
                () -> {
                    for (int i = 0; i < 100; i++) {
                        if (i % 3 == 0) {
                            // 线程礼让
                            Thread.yield();
                            System.out.println("【YIELD】线程礼让," + Thread.currentThread().getName());
                            try {
                                // 延缓执行
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                            System.out.println(Thread.currentThread().getName() + "i = " + i);
                        }
                    }
                }, "嘻嘻线程"
        );

        thread.start();                 // 主线程

        for (int i = 0; i < 100; i++) {
            Thread.sleep(100);
            System.out.println("【礼让主线程就是不一样,跟秀才一样】i = " + i);
        }
    }
}

8、线程优先级的例子:

package com.mydemo;

public class ThreadDemo {

    public static void main(String[] args) {

        // 获取主方法的优先级数值
        System.out.println("主方法的优先级数值:" + Thread.currentThread().getPriority());

        // 线程类对象
        Runnable runnable = () -> {
            for (int i = 0; i < 10; i++) {
                try {
                    // 暂缓执行
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "执行~~~");
            }
        };

        // 线程对象
        Thread threadA = new Thread(runnable, "线程对象A");
        Thread threadB = new Thread(runnable, "线程对象B");
        Thread threadC = new Thread(runnable, "线程对象C");

        // 修改线程对象优先级
        threadA.setPriority(Thread.MIN_PRIORITY);
        threadB.setPriority(Thread.MIN_PRIORITY);
        threadC.setPriority(Thread.MAX_PRIORITY);

        threadA.start();
        threadB.start();
        threadC.start();
    }
}

你可能感兴趣的:(Java)