【Java】创建线程对象两种方式

本文介绍了两种常见的Java线程创建方式:一是通过继承Thread类并重写run方法;二是实现Runnable接口并覆盖run方法。此外,还展示了如何使用ExecutorService来管理和运行线程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.继承Thread类,重载run方法;
Thread t = new Thread(new Runnable() {
    @Override
    public void run() {
        // TODO Auto-generated method stub
    }
});
2.实现Runnable接口,实现run方法;
public class RunnableDemo implements Runnable {

	protected int countDown = 10;
	private static int taskCount = 0;
	private final int id = taskCount++;

	public RunnableDemo() {
	}

	public RunnableDemo(int countDown) {
		this.countDown = countDown;
	}

	public String status() {
		return "#" + id + "(" + (countDown > 0 ? countDown : "LiftOff!") + ").";
	}

	@Override
	public void run() {
		while (countDown-- > 0) {
			System.out.print(status());
			Thread.yield();// 将CPU从一个线程转移给另一个线程
		}
	}

	public static void main(String[] args) {

		System.out.println("这个任务的run()不是单独的线程驱动,是在main()中直接调用");
		RunnableDemo launch = new RunnableDemo();
		launch.run();
		System.out.println();
		System.out.println("************************************");

		System.out.println("在新线程中启动任务");
		Thread thread = new Thread(new RunnableDemo());
		thread.start();
		System.out.println("Waiting for LiftOff");
		System.out.println("************************************");

		System.out.println("添加多个线程去驱动更多的任务");
		for (int i = 0; i < 5; i++) {
			new Thread(new RunnableDemo()).start();
		}
		System.out.println("Waiting for LiftOff");

		System.out.println("************************************");
		System.out.println("使用executor");
		ExecutorService exec = Executors.newCachedThreadPool();
		exec=Executors.newFixedThreadPool(5);
		for (int i = 0; i < 5; i++) {
			exec.execute(new RunnableDemo());
		}
		exec.shutdown();
		
		Thread t=new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
			}
		});
	}

}

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值