一、Java线程实现方式

1.继承Thread类

Thread类本质是实现了Runnable 接口的一个实例。启动线程的唯一方法就是通过Thread 类的start() 方法。start() 方法是一个native 方法,它将启动一个新线程,并执行run() 方法。

public class MyThread extends Thread {
	public void run() {
		System.out.println("MyThread.run()");
	}
}
	MyThread myThread1 = new MyThread();
	myThread1.start();

2.实现Runnable接口

如果自己的类已经extends 另一个类,就无法直接extends Thread,此时可以实现一个
Runnable 接口。

	public class MyThread extends OtherClass implements Runnable {
		public void run() {
			System.out.println("MyThread.run()");
		}
	}
	//启动MyThread,需要首先实例化一个Thread,并传入自己的MyThread 实例:
    MyThread myThread = new MyThread();
    Thread thread = new Thread(myThread);
    thread.start();
    //事实上,当传入一个Runnable target 参数给Thread 后,Thread 的run()方法就会调用
    target.run()
    public void run() {
        if (target != null) {
            target.run();
        }
    }

3.ExecutorService、Callable、Future有返回值线程

有返回值的任务必须实现Callable 接口,类似的,无返回值的任务必须Runnable 接口。执行Callable 任务后,可以获取一个Future 的对象,在该对象上调用get 就可以获取到Callable 任务返回的Object 了,再结合线程池接口ExecutorService 就可以实现传说中有返回结果的多线程了。

	//创建一个线程池
    ExecutorService pool = Executors.newFixedThreadPool(taskSize);
    // 创建多个有返回值的任务
    List<Future> list = new ArrayList<Future>();
    for (int i = 0; i < taskSize; i++) {
        Callable c = new MyCallable(i + " ");
        // 执行任务并获取Future 对象
        Future f = pool.submit(c);
        list.add(f);
        }
    // 关闭线程池
    pool.shutdown();
    // 获取所有并发任务的运行结果
    for (Future f : list) {
        // 从Future 对象上获取任务的返回值,并输出到控制台
        System.out.println("res:" + f.get().toString());
    }

4.基于线程池的方式

线程和数据库连接这些资源都是非常宝贵的资源。那么每次需要的时候创建,不需要的时候销毁,是非常浪费资源的。那么我们就可以使用缓存的策略,也就是使用线程池。

// 创建线程池
ExecutorService threadPool = Executors.newFixedThreadPool(10);
while(true) {
	threadPool.execute(new Runnable() { // 提交多个线程任务,并执行
		@Override
		public void run() {
			System.out.println(Thread.currentThread().getName() + " is running ..");
			try {
			Thread.sleep(3000);
			} catch (InterruptedException e) {
			e.printStackTrace();
			}
		}
	});
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值