s-day06--使用synchornized方法解决线程安全问题
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
package com.inmind.synchornized_method06;
|
||||
|
||||
//同步方法来解决线程安全问题
|
||||
/*
|
||||
同步方法:就是在整个方法体的所有代码上加上同步代码块的功能
|
||||
|
||||
同步方法中有没有锁对象呢???
|
||||
同步成员方法的锁对象:this
|
||||
同步静态方法的锁对象:Class对象(反射)
|
||||
*/
|
||||
public class Demo06 {
|
||||
public static void main(String[] args) {
|
||||
//多个窗口来卖票
|
||||
//1.创建1个卖票的任务
|
||||
TicketTask ticketTask = new TicketTask();
|
||||
//2.创建3个窗口(线程),执行卖票的任务
|
||||
new Thread(ticketTask,"窗口1").start();
|
||||
new Thread(ticketTask,"窗口2").start();
|
||||
new Thread(ticketTask,"窗口3 ").start();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.inmind.synchornized_method06;
|
||||
|
||||
// 1.定义卖票任务,只有100张票,有票就卖
|
||||
public class TicketTask implements Runnable{
|
||||
int ticketCount = 100;//100张票
|
||||
|
||||
Object lock = new Object();//创建一个对象
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
//有票就卖
|
||||
while (true) {
|
||||
// synchronized (lock){
|
||||
sellTicket();
|
||||
// }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//线程安全的同步的卖票方法
|
||||
private synchronized void sellTicket() {
|
||||
//具有线程安全问题的代码
|
||||
if (ticketCount > 0) {
|
||||
//卖票:需要耗时5ms
|
||||
try {
|
||||
Thread.sleep(50);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
System.out.println(Thread.currentThread().getName() + "正在卖第" + ticketCount + "张票");
|
||||
ticketCount--;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user