多线程--总结Thread类的基本用法

1 : 线程创建

线程的创建总共分为三种方式

1.1 : 继承Thread创建线程

// 创建线程的方法:继承Thread类
// 缺点:java是单继承,所以继承了Thread类后便不能继承其它类了

public class Create_Of_Thread extends Thread{
    //实现Thread类中的抽象方法
    @Override
    public void run() {
        System.out.println("创建了一个线程");
    }

    public static void main(String[] args) {
        Thread thread = new Create_Of_Thread();//向上转型
        thread.start();//启动线程
        //调用star()方法后才会创建线程,之后才会调用run()方法

        //1:方法性质不同:
        //          run 是一个普通方法,而 start 是开启新线程的方法。
        //2:执行速度不同:
        //          调用 run 方法会立即执行任务,
        //          调用 start 方法是将线程的状态改为就绪状态,不会立即执行。
        //3:调用次数不同:
        //          run 方法可以被重复调用,而 start 方法只能被调用一次


        //使用匿名内部类创建线程
        Thread thread_0 = new Thread(){
            @Override
            public void run() {
                System.out.println("使用匿名内部类创建线程");
            }
        };
        thread_0.start();
    }
}

1.2 : 实现Runnable接口创建线程

// 实现Runnable接口来创建线程,
// Runnable接口实际上就是一个函数接口,链接Thread类中的run函数
public class Create_Of_Runnable implements Runnable{
    //覆写run方法
    @Override
    public void run() {
        System.out.println("create a thread");
    }

    //该类实现了Runnable接口
    private static class Im_Test implements Runnable{
        //覆写Runnable接口中的run函数
        @Override
        public void run() {
            System.out.println("这是一个线程");
        }
    }

    public static void main(String[] args) {
        Im_Test test = new Im_Test();
        Thread thread_test = new Thread(test);
        thread_test.start();


        Create_Of_Runnable a = new Create_Of_Runnable();
        Thread thread_a = new Thread(a);
        thread_a.start();
        //Thread类的构造方法中允许传入一个_实现了Runnable接口的对象_作为参数创建一个线程

        //匿名内部类
        new Runnable(){
            @Override
            public void run() {
                System.out.println("使用匿名内部类创建线程");
            }
        };
        //使用其创建线程
        Thread thread_0 = new Thread(new Runnable(){
            @Override
            public void run() {
                System.out.println("使用匿名内部类创建线程");
            }
        });
        thread_0.start();


        //使用lambda表达式创建线程
        Thread thread_l = new Thread(()->{
            System.out.println("使用lambda表达式创建线程");
        });
        thread_l.start();

    }
}

1.3 : 实现Callable接口创建线程 (可以返回结果值)

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

//实现Callable接口可以创建可以有返回值的线程
public class Create_Of_Callable  {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //使用匿名Callable实现线程返回值
        FutureTask<Integer> task = new FutureTask<>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                return 1000;
            }
        });

        Thread thread = new Thread(task);
        thread.start();
        int result = task.get();
        System.out.println("线程返回值是"+result);
    }

}

//实现接口时可以指定类型,也可以不指定
class Test_Callable implements Callable<Integer>{
    //覆写接口的抽象方法
    @Override
    public Integer call() throws Exception {
        return 100;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //创建实现Callable接口的对象
        Test_Callable callable = new Test_Callable();
        //Callable需要配合FutureTask使用
        FutureTask<Integer> task = new FutureTask<>(callable);
        //创建线程
        Thread thread = new Thread(task);
        //启动线程
        thread.start();
        //使用FutureTask对象接受返回值,并且需要抛出异常
        int result = task.get();
        System.out.println("返回结果是"+ result);

    }
}

2 : 线程中断

2.1 : 自定义标识符中断线程

public class End_Of_Customization {

    private static volatile boolean flag=false;//自定义标识符
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("开始执行");
                while(!flag){
                    try {
                        Thread.sleep(1000);//线程休眠1s
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("线程结束");
            }
        });
        thread.start();
        flag=true;
    }
    // 自定义中断标识符的问题在于:线程中断的不够及时。
    // 因为线程在执行过程中,无法调用 while(!isInterrupt) 来判断线程是否为终止状态,
    // 它只能在下一轮运行时判断是否要终止当前线程,所以它中断线程不够及时
}

2.2 : 使用线程中断方法 interrupt 停止线程

public class End_Of_Interrupt {
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程开始");
                while(true){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        System.out.println("线程结束");
                        break;
                    }
                }
            }
        });
        thread.start();
        thread.interrupt();
    }
    // 使用 interrupt 方法可以给执行任务的线程,发送一个中断线程的指令,
    // 它并不直接中断线程,而是发送一个中断线程的信号,把是否正在中断线程的主动权交给代码编写者。
    // 相比于自定义中断标识符而然,它能更及时的接收到中断指令
}

2.3 : 使用 stop 停止线程

stop 方法虽然可以停止线程,但它已经是不建议使用的废弃方法了

3 : 线程等待

使用join()方法可以使主线程等待thread执行完毕。

public class Thread_Join {
    static int sum=0;
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10000; i++) {
                    sum++;
                }
                //执行完for循环的话,sum==10000
            }
        });

        thread.start();
        thread.join();//使用join需要抛出一个异常 InterruptedException
        //若没有join语句的话,sum < 10000(thread未执行完,或未执行,主线程就结束了)
        System.out.println(sum);
    }

}

4 : 线程休眠

4.1 : 使用sleep休眠


public class Thread_Sleep {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("开始执行");
                try {
                    //调用sleep需要用try-catch包裹
                    System.out.println("开始休眠");
                    Thread.sleep(1000);
                    System.out.println("休眠结束");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程结束");
            }
        });
        thread.start();
        //Thread.sleep(int ms);
        //该方法可以使当前线程休眠,传入的数字单位为ms(毫秒)\
        //使用该方法需要进行异常处理 
    }

}

4.2 : 使用 TimeUnit 休眠

import java.util.concurrent.TimeUnit;

public class Thread_TimeUnit {

    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.DAYS.sleep(1);//天
                    TimeUnit.HOURS.sleep(1);//⼩时
                    TimeUnit.MINUTES.sleep(1);//分
                    TimeUnit.SECONDS.sleep(1);//秒
                    TimeUnit.MILLISECONDS.sleep(1000);//毫秒
                    TimeUnit.MICROSECONDS.sleep(1000);//微妙
                    TimeUnit.NANOSECONDS.sleep(1000);//纳秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        //TimeUnit 的内部实现其实还是sleep,只是包装了一下sleep,让它更好用
    }
}

5 : 获取线程实例

public class Test_2 {
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                //使用currentThread可以得到当前线程
                String name = Thread.currentThread().getName();
                System.out.println(name);
            }
        },"测试线程_1");

        thread.start();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值