多线程对于数据安全数据同步的小demo:
有两种方式:①,同步代码块如:可以在方法中植入同步代码块
synchronized (this) {//同步代码块
System.out.println("Thread:"+Thread.currentThread().getName()+":count:"+count);
count--;
}
②,同步方法
@Override
public void run() {
System.out.println("+++++++:"+count);
while(true){
syMethod();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private synchronized void syMethod() {//同步方法
if(count>0){
System.out.println("Thread:"+Thread.currentThread().getName()+":count:"+count);
count--;
}
}
①,代码:同步代码块
public class SaleTicketDemo implements Runnable{
private int count=1000;
Object obj = new Object();
/**
* 处理卖票逻辑
* @see java.lang.Runnable#run()
* @author wf 2015-11-30 下午4:02:40
*/
@Override
public void run() {
System.out.println("+++++++:"+count);
try {
System.out.println("Thread:"+Thread.currentThread().getName());
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sale();
System.out.println("===============:"+count);
}
private void sale() {
while(true){
synchronized (this) {//同步代码块
if(count>0){
System.out.println("Thread:"+Thread.currentThread().getName()+":count:"+count);
count--;
}else{
return;
}
}
}
}