package com.aflfte.syn;
/**
* 线程安全:在并发时保证数据的准确性,效率尽可能高
* 通过Synchronized实现
* 1、同步方法
* 2、同步块
*
* @author jinhao
*
*/
public class SynTest01 {
public static void main(String[] args) {
SafeWeb12306 web=new SafeWeb12306();
new Thread(web,"张三").start();
new Thread(web,"李四").start();
new Thread(web,"王五").start();
}
}
class SafeWeb12306 implements Runnable {
private int ticketNum=100;
private boolean flag=true;
@Override
public void run() {
// TODO 自动生成的方法存根
while(flag) {
test();
}
}
//线程安全;也叫同步并发
public synchronized void test() {//同步方法
if(ticketNum<=0) {
flag=false;
return ;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->"+ticketNum--);
}
}
package com.aflfte.syn;
/**
* 同步块的使用
* @author jinhao
*
*/
public class SynTest02 {
public static void main(String[] args) {
//帐户
Account account=new Account(100, "结婚礼金");
SafeDrawing you=new SafeDrawing(account, 80, "可悲的你");
SafeDrawing wife=new SafeDrawing(account, 90, "嗨皮的她");
you.start();
wife.start();
}
}
//帐户
//模拟取款机
class SafeDrawing extends Thread{
Account accunt;//取款帐户
int drawingMoney;//取钱金额
int drawingTotal;//钱的总数
public SafeDrawing(Account accunt, int drawingMoney,String name) {
super(name);
this.accunt = accunt;
this.drawingMoney = drawingMoney;
}
@Override
public void run() {
test();
}
public void test() {
if(accunt.money<=0) {//提高性能
return;
}
synchronized (accunt) {//同步块使用
if(accunt.money-drawingMoney<0) {
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
accunt.money-=drawingMoney;
drawingTotal+=drawingMoney;
System.out.println(this.getName()+"-->帐户余额:"+accunt.money);
System.out.println(this.getName()+"-->总取款为:"+drawingTotal);
}
}
}
« 并发模拟示例
|
线程的其它方法»
|