四种创建线程的方法

1)继承Thread类创建线程

2)实现Runnable接口创建线程

3)使用Callable和Future创建线程

4)使用线程池例如用Executor框架

线程状态

第一种:继承Thread类创建线程


/*
* @description 继承Thread类实现多线程的格式
* author zhangyanfen
* @date 2023/1/30 16:57
*/
public class TestDemo01 extends Thread{
    private Thread t;
    private String threadName;

    public TestDemo01(String name) {
        this.threadName = name;
        System.out.println("构造器声明   "+threadName);
    }
    //重写父类方法
    @Override
    public void run(){
        System.out.println("运行 "+threadName);
        try {
            for (int i = 10; i > 0; i--) {
                System.out.println("线程名称: " + threadName + ", " + i);
                //线程睡眠
                Thread.sleep(100);
            }
        } catch(InterruptedException e) {
            System.out.println(threadName+"中断");
        }
        System.out.println(threadName+"退出");
    }

    @Override
    public void start(){
        System.out.println(threadName+"开始工作");
        if (t==null) {
            t = new Thread(this,threadName);
            t.start();
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TestDemo01 t1=new TestDemo01("wang-1");
        t1.start();

        TestDemo01 t2=new TestDemo01("wang-2");
        t2.start();
    }
}

第二种:实现Runnable接口

在Java 5之后,任务分两类:一类是实现了Runnable接口的类,一类是实现了Callable接口的类。两者都可以被ExecutorService执行,但是Runnable任务没有返回值,而Callable任务有返回值。并且Callable的call()方法只能通过ExecutorService的submit(Callable<T> task) 方法来执行,并且返回一个 <T>Future<T>,是表示任务等待完成的 Future。

如果Future的返回尚未完成,则get()方法会阻塞等待,直到Future完成返回,可以通过调用isDone()方法判断Future是否完成了返回。

/*
 * @description 通过实现Runnable接口
 * author zhangyanfen
 * @date 2023/1/30 16:57
 */
public class TestDemo02 implements Runnable {
    private String threadName;

    public TestDemo02(String threadName) {
        this.threadName=threadName;
    }
    @Override
    public void run() {
        System.out.println(threadName);
        for(int i=0;i<10;i++) {
            System.out.println("线程--"+threadName+"--"+i);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("线程*"+threadName+"*执行结束");
    }
    public static void main(String[] args) {
        TestDemo02 t1=new TestDemo02("张三");
        TestDemo02 t2=new TestDemo02("李四");
        Thread zhangsan=new Thread(t1);
        Thread lisi=new Thread(t2);
        zhangsan.start();
        lisi.start();
    }
}

第三种:使用Callable和Future创建线程

import java.util.concurrent.*;

/*
 * @description 通过线程池来实现
 * author zhangyanfen
 * @date 2023/1/30 16:57
 */
public class TestDemo04 implements Callable<Boolean> {
    private String name;

    public TestDemo04(String name) {
        this.name = name;
    }

    @Override
    public Boolean call() {
        //获取当前时间
        long time1 = System.currentTimeMillis();
        System.out.println(Thread.currentThread().getName() + "当前时间为:" + time1);
        return Thread.currentThread().isAlive();
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<Boolean> threadTask = new FutureTask<>(new TestDemo04("李四"));
        ExecutorService service = new ThreadPoolExecutor(5, 5, 5, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(10),
                new ThreadPoolExecutor.DiscardOldestPolicy()
        );
        Future f = service.submit(threadTask);
        System.out.println("得到的结果:" + threadTask.get() + ", F的内容:" + f.get());
    }
}

第四种:使用线程池例如用Executor

Java通过Executors提供四种线程池,分别为

newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行

CachedThreadPool线程池为无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。

ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
    final int index = i;
    try {
        Thread.sleep(index * 1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    cachedThreadPool.execute(new Runnable() {

        @Override
        public void run() {
            System.out.println(index);
        }
    });
}

newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) {
    final int index = i;
    fixedThreadPool.execute(new Runnable() {

        @Override
        public void run() {
            try {
                System.out.println(index);
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
}

newScheduledThreadPool创建一个定长线程池,支持定时及周期性任务执行

ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
scheduledThreadPool.schedule(new Runnable() {

    @Override
    public void run() {
        System.out.println("delay 3 seconds");
    }
}, 3, TimeUnit.SECONDS);

另一种执行方法

scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("delay 1 seconds, and excute every 3 seconds");
}
}, 1, 3, TimeUnit.SECONDS);

newSingleThreadExecutor创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行

ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
    final int index = i;
    singleThreadExecutor.execute(new Runnable() {

        @Override
        public void run() {
            try {
                System.out.println(index);
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
}

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值