Thread 类的基本用法(附代码)

目录

一、线程创建

(1)继承 Thread 来创建线程

(2)实现 Runnable 接口来创建线程

(3)匿名内部类创建 Thread 子类对象

(4)匿名内部类创建 Runnable 子类对象

(5)Lambda 表达式创建 Runnable 子类对象

二、线程中断

(1)自定义标志位来控制线程是否结束

(2)通过使用标准库自带的标志位对线程进行结束

三、线程等待

四、线程休眠

五、获取线程实例


一、线程创建

(1)继承 Thread 来创建线程

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("继承Thread方法重写run方法来创建线程");
    }
}
public class TestThread1 {

    public static void main(String[] args) {
        MyThread myThread1 = new MyThread();
        myThread1.start();
    }
}

(2)实现 Runnable 接口来创建线程

class MyRunnable implements Runnable{
    @Override
    public void run() {
        System.out.println("通过实现Runnable接口,重写run方法来创建线程");
    }
}

public class TestThread2 {
    public static void main(String[] args) {
        Thread t = new Thread(new MyRunnable());
        t.start();
    }
}

(3)匿名内部类创建 Thread 子类对象

public class TestThread3 {
    public static void main(String[] args) {
        Thread t = new Thread() {
            @Override
            public void run() {
                System.out.println("匿名内部类创建 Thread 子类对象");
            }
        };
        t.start();
    }
}

(4)匿名内部类创建 Runnable 子类对象

public class TestThread4 {
    public static void main(String[] args) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("匿名内部类创建 Runnable 子类对象");
            }
        });
        t.start();
    }
}

(5)Lambda 表达式创建 Runnable 子类对象

public class TestThread5 {
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            System.out.println("使用 lambda 表达式创建线程");
        });
        t.start();
    }
}

二、线程中断

(1)自定义标志位来控制线程是否结束

public class InterruptedThread1 {
    private static boolean isQuit; //自定义标志位
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            while (!isQuit) {
                System.out.println(Thread.currentThread().getName() + ": 我还活着");
                try {
                    Thread.sleep(1000);//让线程堵塞1s
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        isQuit = true; //设置自定义标志位
        System.out.println("设置让t线程结束");
    }
}

(2)通过使用标准库自带的标志位对线程进行结束

要注意的是interrupted方法的行为有两种

1.如果 t 线程在运行状态会设置标志位为true

2.如果 t 线程在堵塞状态(sleep)不会设置标记位(这里不是没设置标志位,只是设置后sleep/wait等阻塞方法会清除标志位),而是触发中断异常,这个异常会把sleep提前唤醒

  • 假设出现第二种情况就需要检测到异常后自行选择结不结束线程
public class InterruptedThread2 {
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println(Thread.currentThread().getName() + ": 我还活着");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;//检测到异常后跳出循环从而让线程结束
                }
            }
            System.out.println("t线程执行完了");
        });
        t.start();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t.interrupt();
        System.out.println("设置让t线程结束");
    }
}

三、线程等待

线程之间的调度是不一样的,咱们就可以调用 join 来对线程执行顺序做出干扰,来控制线程之间的结束顺序。

在main中调用 t.join() 就会使main线程阻塞等待,等线程 t 执行完后main才继续执行。

public class TestJoin {
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + "我在运行");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();

        System.out.println("t.join前");
        try {
            t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("t.join后");
    }
}

四、线程休眠

        线程调用sleep就是让线程堵塞休息一会,例如 thread.sleep(1000) 就可以让线程thread堵塞1秒。

public class TestThreadSleep {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("线程开始休眠五秒");
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);//休眠1秒
                    System.out.println(i+1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("已经休眠了五秒");
        });
        thread.start();
    }
}

五、获取线程实例

 

Thread.currentThread()这个方法在哪个线程里调用就返回哪个线程的对象引用 

public class TestcurrentThread {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName());
    }
}

谢谢您的观看,如有错误还请指正!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Thread实现阶乘的方法如下: 首先,我们需要创建一个继承自Thread的阶乘计算线程。在该中,我们需要重写Thread的run()方法,并在该方法中实现阶乘的计算逻辑。 在run()方法中,我们需要定义一个变量来存储阶乘的结果,然后使用for循环来逐步计算阶乘的每一项,将计算的结果累乘到结果变量中。最后,我们可以将计算结果输出到控制台。 接下来,我们需要在主线程中创建并启动阶乘计算线程。我们可以通过创建该线程的实例对象,并调用其start()方法来实现线程的启动。在调用start()方法后,线程会自动执行该线程中的run()方法。 以下是使用Thread完成阶乘计算的示例代码: ```java public class FactorialThread extends Thread { private int number; public FactorialThread(int number) { this.number = number; } @Override public void run() { int result = 1; for (int i = 1; i <= number; i++) { result *= i; } System.out.println(number + "的阶乘为:" + result); } } public class Main { public static void main(String[] args) { int number = 5; FactorialThread factorialThread = new FactorialThread(number); factorialThread.start(); } } ``` 在上述代码中,我们创建了一个名为FactorialThread的阶乘计算线程,并在主线程中创建了一个number为5的实例对象。然后,我们通过调用start()方法来启动该线程,使其开始执行阶乘计算逻辑。最终,程序会输出5的阶乘结果。 需要注意的是,上述代码只是简单示例了使用Thread来完成阶乘计算的过程,并未考虑线程的安全性和效率。在实际应用中,可能需要使用更加复杂的线程同步机制来确保计算的正确性,并进行性能优化以提高计算效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值