多线程随记

多线程的的实现方式无非就是两种,一种是继承thread类,另一种是实现runable接口。


继承thread类

public class SynchornizeTest extends Thread{
	 private String name;

	public SynchornizeTest(String name) {
		super();
		this.name = name;
	}
	
	public  void run(){
		for(int i=0;i<5;i++){
			System.out.println(name+"第"+i+"次");
		}
	}
	public static void main(String[] args) {
		SynchornizeTest thread1 = new SynchornizeTest("张三");
		SynchornizeTest thread2 = new SynchornizeTest("李四");
		thread1.start();
		thread2.start();
		
	}

}
结果为:


实现runable

public class SynchornizeTest implements Runnable{
	 private String name;

	public SynchornizeTest(String name) {
		super();
		this.name = name;
	}
	
	public  void run(){
		for(int i=0;i<5;i++){
			System.out.println(Thread.currentThread().getName()+"第"+i+"次");
		}
	}
	public static void main(String[] args) {
		SynchornizeTest thread1 = new SynchornizeTest("张三");
		Thread t1=new Thread(thread1,"thread1");
		SynchornizeTest thread2 = new SynchornizeTest("李四");
		Thread t2=new Thread(thread2,"thread2");
		t1.start();
		t2.start();
	}

}
结果:



从上述的两种不同的方式来看,都是通过run方法来实现的多线程,在我们实现runable接口来时,我们先要创建一个实现了runable的一个类对象,之后我们再创建一个线程并将对象传入。



(ps:这只是为了能够记住一下线程的实现方式的一个笔记)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值