s-day06-使用synchornized方法解决线程安全问题
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
package com.inmind.thread_safet_method06;
|
||||
|
||||
/*
|
||||
在java中可以使用一个关键字synchronized来解决线程安全问题.
|
||||
|
||||
synchronized能够修饰代码块和方法,修饰代码块之后就被称之为同步代码块,修饰方法之后就被称之为同步方法
|
||||
|
||||
同步方法语法:
|
||||
修饰符 synchronized 返回值类型 方法名(参数列表){
|
||||
方法体
|
||||
}
|
||||
|
||||
同步方法:就是在整个方法体的所有代码上都加上同步代码块
|
||||
*/
|
||||
public class Demo07 {
|
||||
public static void main(String[] args) {
|
||||
//创建卖票任务
|
||||
TicketTask ticketTask = new TicketTask();
|
||||
new Thread(ticketTask, "窗口1").start();
|
||||
new Thread(ticketTask,"窗口2").start();
|
||||
new Thread(ticketTask,"窗口3").start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.inmind.thread_safet_method06;
|
||||
|
||||
//卖票任务:就是卖100张票
|
||||
public class TicketTask implements Runnable{
|
||||
int ticketCount = 100;//100张票
|
||||
Object lock = new Object();//锁对象
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
//有票就卖
|
||||
while (true) {
|
||||
//如果有票就卖
|
||||
sellTicket();
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
卖票方法(同步方法)
|
||||
同步方法中有没有锁对象呢????
|
||||
同步成员方法的锁对象:this
|
||||
同步静态方法的锁对象:TicketTask.class(Class对象)【反射中学习】
|
||||
*/
|
||||
public synchronized void sellTicket(){
|
||||
if (ticketCount > 0) {
|
||||
//模拟卖票时间
|
||||
try {
|
||||
Thread.sleep(50);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
System.out.println(Thread.currentThread().getName() + "正在卖第" + ticketCount + "张票");
|
||||
ticketCount--;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user