java多线程的两种创建方式

1.继承Thread类

2.实现Runnable接口(并发资源问题)

线程与进程不同,进程的内存是单独的,而线程是共用的,这里的共用体现在了如果你创建了一个资源对象,再用这个资源对象创建出的线程对象的内存是共用的。

  1. 继承Thread类
    这个方法好处是代码写起来简洁,因为本身就是线程了,但坏处就是有些需要继承父类的类不能用这个方法,所以使用第二种实现接口的方法会更好。
public class MutiThreadClient {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new MutiThread("Thread A").start();
		new MutiThread("Thread B").start();
		new MutiThread("Thread C").start();
	}

}
public class MutiThread extends Thread{
	private String str;
	public MutiThread(String str) {
		this.str=str;
	}
	public void run() {//每个线程在main类调用start()方法后都会转到run()
		System.out.println("Hello!"+str);
	}
	

}

输出异步的。

Hello!Thread A
Hello!Thread C
Hello!Thread B

  1. 实现Runnable接口
    避免了java单继承的局限,更好的选择,而且资源对象也被单独出来了,更符合java面向对象的思想。
public class RunnableClient {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new Thread(new RunnableThread("Thread A")).start();
		new Thread(new RunnableThread("Thread B")).start();
		new Thread(new RunnableThread("Thread C")).start();
	}

}
public class RunnableThread implements Runnable {
	private String str;
	public RunnableThread(String str) {
		this.str=str;
	}
	public void run() {
		System.out.println("Hello!"+str);
	}

}

并发资源问题

public class MutiThreadClient {

	public static void main(String[] args) {
		RunnableThread rt = new RunnableThread(); // 定义资源对象
		new Thread(rt).start(); // 第一个线程启动
		new Thread(rt).start(); // 第二个线程启动
		new Thread(rt).start(); // 第三个线程启动
		}


}


public class RunnableThread implements Runnable {
	private int ticket = 5; // 定义总票数

	@Override
	public void run() { // 线程的主体方法
		for (int x = 0; x < 100; x++) { // 进行100次的卖票处理
			if (this.ticket > 0) { // 有剩余票
				System.out.println("卖票,ticket = " + this.ticket--);
			}
		}
	}

}

output:

卖票,ticket = 5
卖票,ticket = 3
卖票,ticket = 1
卖票,ticket = 4
卖票,ticket = 2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值