java线程

创建线程

  1. 继承Thread类 重新 run方法
public class CreateTread1 extends Thread{
    @Override
    public void run() {
        int i=0;
        while (i<10000){
            System.out.println(i++);
        }
    }
}

实现类

public class CreateThread2 {
    public static void main(String[] args) {
       Thread thread = new CreateTread1();
       thread.start();
    }
}

  1. 实现Runnable接口,重写run方法,根据实例创建thread对象,thread.start()开启
public class CreateTread1 implements Runnable {
    @Override
    public void run() {
        int i=0;
        while (i<10000){
            System.out.println(i++);
        }
    }
}

实现类

Thread thread = new Thread(new CreateTread1());
thread.start();

特别实现 – Lambda表达式与双冒号

public class CreateThread2 {


    public static void main(String[] args) {
        //Lambda表达式写入run方法
       Runnable runnable1 = ()->{
           int i=0;
         while (i<10000){
             System.out.println(i++);
         }
       };
       //双冒号::调用 CreateTread3 中的 MyMethod 方法 写入run方法
       Runnable runnable = CreateTread3::MyMethod;


        Thread thread3 = new Thread(runnable);
        Thread thread2 = new Thread(runnable1);
       thread3.start();
       thread2.start();
    }
}
class CreateTread3{

    public static void MyMethod(){
        System.out.println("运行");
    }
}
  1. 实现Callable接口,重写call方法,创建FutureTask的实例并传入实现类的对象,再创建thread对象并传入FutureTask的对象,thread.start()开启,通过FutrueTask的对象的get方法得到call方法的返回值
public class CreateThread2 {


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask futureTask = new FutureTask(new CreateTread3());

        Thread thread = new Thread(futureTask);
        thread.start();
        System.out.println(futureTask.get());
    }
}
class CreateTread3 implements Callable {


    @Override
    public Object call() throws Exception {
        int i =0;
        while (i<10000){
            System.out.println("运行"+i++);
        }

        return i;//返回10000
    }
}

测试写法

		Callable callable = ()->{
            System.out.println("运行");
            return "运行完毕";
        };
        FutureTask futureTask2 = new FutureTask(callable);
        Thread thread2 = new Thread(futureTask2);
        thread2.start();
        System.out.println(futureTask2.get());

停止线程


        Thread thread3 = new Thread(){
            @Override
            public void run() {
                int i =0;
                if (!interrupted()){
                    System.out.println("停止运行了"+i);
                }
            }
        };
        thread3.start();

        thread3.sleep(1000);
        thread3.interrupt();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值