多线程(一)——通过实现Runnable接口创建线程

/*
	The second way of creating a thread.
	Implement Runnable interface,processes as following:
	1.Define a class and implement Runnable interface;
	2.Rewrite the run method in Runnable interface;
	3.Create a object through Thread class;
	4.Throw the son-class object of Runnable to constructor
	  of Thread class as real argument;	
	5.Call the start method of Thread class so the Thread 
	  will start and call Runnable interface.
*/

class Ticket implements Runnable
{
	private int tick = 100;
	public void run()
	{
		while(true)
		{
			if(tick>0)
			{
				System.out.println(Thread.currentThread().getName()+"------sale:"+tick--);
			}
		}
	}
}

class TicketDemo2
{
	public static void main(String[] args)
	{
		Ticket t = new Ticket();
		Thread t1 = new Thread(t);
		Thread t2 = new Thread(t);
		Thread t3 = new Thread(t);
		Thread t4 = new Thread(t);
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
多线程可以通过以下三种方式创建: 1. 实现Runnable接口,并实现run()方法。首先,自定义一个类并实现Runnable接口,然后在该类中实现run()方法。接下来,创建Thread对象,并将实现Runnable接口的对象作为参数实例化该Thread对象。最后,调用Thread的start()方法来启动线程。这种方式的代码示例可以参考引用\[1\]中的代码。 2. 继承Thread类,重写run()方法。Thread类本质上也是实现Runnable接口一个实例,它代表了一个线程的实例。通过继承Thread类并重写run()方法,然后调用start()方法来启动线程。这种方式的代码示例可以参考引用\[2\]中的代码。 3. 使用匿名内部类实现多线程。可以直接在创建Thread对象时使用匿名内部类来实现多线程。这种方式可以简化代码,但只能使用一次。具体的代码示例可以参考引用\[3\]中的代码。 总结起来,多线程创建方式实现Runnable接口、继承Thread类和使用匿名内部类。每种方式都有其适用的场景,可以根据具体需求选择合适的方式创建多线程。 #### 引用[.reference_title] - *1* *2* [初识多线程——创建多线程的三种方式](https://blog.csdn.net/pizssn/article/details/106382025)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [多线程创建的三种方式](https://blog.csdn.net/qq_31780525/article/details/54338341)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值