线程,线程同步,对象锁,同步方法

线程,线程同步,对象锁,同步方法

/**
 * @author Administrator 模拟火车站卖票窗口 用实现的方式,此时的Ticket只是一个普通的类 在用实现的方式的时候,必须要
 *         implements Runnable 接口
 */
public class Ticket implements Runnable {
int count = 100;
Object obj = new Object();
//

@Override
public void run() {
while (true) {
// 线程同步,能保证共享数据的安全,给一个对象锁,其类型是Object的即可,但是要保证是同一个
// 用对象锁实现线程的同步,以保证数据的安全
/*
* synchronized (this.getClass()) {

* if (count > 0) {
* System.out.println(Thread.currentThread().getName() + "卖出票号为" +
* count--); } else { break; }

* }
*/


// 用同步方法实现线程的同步


show();
}
}


//同步方法加关键字  synchronized 将需要同步的代码写到同步方法中(共享数据)

public synchronized void show() {
if (count > 0) {
System.out.println(Thread.currentThread().getName() + "卖出票号为" + count--);
} else {
return;
}
}

}




/**
 * 测试类
 * 
 * @author Administrator
 *
 */
public class Test_Ticket {
public static void main(String[] args) {


// 创建一个票窗口
Ticket ticket = new Ticket();


// new Thread(Runable r,String name) 可以创建一个线程 别给其起名字

// 创建窗口1
Thread thread1 = new Thread(ticket, "窗口1");
// 创建窗口2
Thread thread2 = new Thread(ticket, "窗口2");
// 创建窗口3
Thread thread3 = new Thread(ticket, "窗口3");


// 开始线程
thread1.start();
thread2.start();
thread3.start();


}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值