继承Thread和实现Runnable方式的两种对比

实现Runnable方式要比继承Thread方式好

①避免单继承的局限性 ②如果需要多个线程处理同一资源(共享数据),Threrad方式变量需要static修饰

注意:synchronized同步代码块的时候,线程安全地问题,所有的线程需要共用一把锁

package com.shn.juc.thread;
// 模拟火车站售票窗口:三个窗口一共100张票
public class WindowsSaleTicket {

	public static void main(String[] args) {
		int tickets = 10;
		SubWindowThread subWindowThread1 = new SubWindowThread();
		SubWindowThread subWindowThread2 = new SubWindowThread();
		SubWindowThread subWindowThread3 = new SubWindowThread();
		subWindowThread1.setName("窗口1");
		subWindowThread2.setName("窗口2");
		subWindowThread3.setName("窗口3");

		subWindowThread1.start();
		subWindowThread2.start();
		subWindowThread3.start();
	}
}

class SubWindowThread extends Thread{
	static int tickets=10;//剩余票数,三个窗口公用,所以需要用static修饰,成为类变量
	static Object obj  = new Object();
	public void run(){
		while(true){
			synchronized(obj){
				if(tickets>0){
					try {
						Thread.currentThread().sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName()+"---"+tickets--);
				}else{
					break;
				}
			}
		}
		
	}
}

 

package com.shn.juc.thread;

public class ImplementRunnableClass {

	public static void main(String[] args) {
		SubWindow sw = new SubWindow();
		Thread t1 = new Thread(sw);
		Thread t2 = new Thread(sw);
		Thread t3 = new Thread(sw);

		t1.start();
		t2.start();
		t3.start();
	}
}
class SubWindow implements Runnable{

	int tickets=10;//剩余票数,三个窗口公用,共享数据
	Object obj = new Object();//三个线程共享的锁,成员变量
	public void run(){
//		Object obj = new Object();//局部变量,各个线程各自的锁,失效
		while(true){
			synchronized(obj){
				if(tickets>0){
					try {
						Thread.currentThread().sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName()+"---"+tickets--);
				}else{
					break;
				}
			}
		}
		
	}
	
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值