java 多线程开发一

在java 中想实现多线程一般有两种方法一种是实现Runnable 一种是继承 Thread 

1.通过继承thread 实现

先看一个例子:

/**
 * @author 曹飛龍
 * 通过继承thread实现多线程
 */
public class Test1 extends Thread {
	private String name;
	public Test1(String name) {
		this.name = name;
	}
	@Override
	public void run() {
		for (int i = 0; i < 5; i++) {
			System.out.println(name + "" + i);
		}
	}
	public static void main(String[] args) {
		  Test1 test1= new Test1("曹飞龙");
		  Test1 test2= new Test1("sun");
		  test1.start();
		  test2.start();
	}
}
//运行效果:
//曹飞龙0
//sun0
//曹飞龙1
//sun1
//曹飞龙2
//sun2
//曹飞龙3
//sun3
//sun4
//曹飞龙4



2. 通过实现Runnable实现多线程

先看一个例子:

/**
 * @author 曹飛龍 
 * 通过实现Runnable实现多线程
 */
public class Test3 implements Runnable {
	private String name;
	public Test3(String name) {
		this.name = name;
	}
	@Override
	public void run() {
		for (int i = 0; i < 5; i++) {
			System.out.println(name + "" + i);
		}
	}
	public static void main(String[] args) {
		Test3 test = new Test3("曹飞龙");
		Test3 test2 = new Test3("sun");
		new Thread(test).start();
		new Thread(test2).start();
	}
}
//运行效果:
//曹飞龙0
//sun0
//曹飞龙1
//sun1
//曹飞龙2
//sun2
//曹飞龙3
//sun3
//sun4
//曹飞龙4

Thread 类也是实现了Runnable

Thread 和 Runnable 的区别:如果一个类继承了Thread类  则不容易实现资源共享 如果实现了Runable借口 则可以实现资源共享。

假设一个卖票的程序

通过继承Thread类实现买票发现票会被重复卖掉

/**
 * @author 曹飛龍 
 * 通过继承Thread实现买票的程序
 */
public class Test4 extends Thread {
	private  int count =5;// 假设当前还有5张票
	private String name ;
	public Test4(String name) {
		super();
		this.name = name;
	}
	@Override
	public void run() {
		while(count>0){
			 System.out.println(name+"买票"+count);
			 count--;
		}
	}
	public static void main(String[] args) {
		Test4 test = new Test4("窗口A");
		Test4 test2 = new Test4("窗口B");
		Test4 test3 = new Test4("窗口C");
		test.start();
		test2.start();
		test3.start();
	}
}
//运行效果:
//窗口A买票5
//窗口C买票5
//窗口B买票5
//窗口C买票4
//窗口A买票4
//窗口C买票3
//窗口B买票4
//窗口C买票2
//窗口C买票1
//窗口A买票3
//窗口A买票2
//窗口A买票1
//窗口B买票3
//窗口B买票2
//窗口B买票1
通过实现Runnable实现买票的程序依然存在一张票被多次卖掉的情况但是实现了资源的共享   被多次卖掉在之后的会有详细的介绍

/**
 * @author 曹飛龍 
 * 通过实现Runnable实现买票程序
 */
public class Test5 implements Runnable {
	private int count = 5;// 假设当前还有5张票
	@Override
	public void run() {
		while (count > 0) {
			System.out.println(Thread.currentThread().getName() + "买票" + count);
			count--;
		}
	}
	public static void main(String[] args) {
		Test5 test = new Test5();
		new Thread(test,"窗口A").start();
		new Thread(test,"窗口B").start();
		new Thread(test,"窗口C").start();
	}
}
// 运行效果:
//窗口A买票5
//窗口B买票5
//窗口C买票5
//窗口B买票3
//窗口B买票1
//窗口A买票4
//窗口C买票2




请参考http://www.cnblogs.com/rollenholt/archive/2011/08/28/2156357.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值