package com.mixian.thread;
public class ThreadSafe extends Thread{
private static int num = 1;
private String username;
public ThreadSafe(String username){
this.username = username;
}
@Override
public void run() {
synchronized(String.valueOf(num)){
if(num>0){
System.out.println("正在检票。。。"+this.getUsername());
System.out.println("正在出票。。。"+this.getUsername());
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("售票完成");
num--;
System.out.println("当前票量+"+num);
}else{
System.out.println("nothing");
}
}
}
public static void main(String[] args) {
try {
new ThreadSafe("mxiian").start();
Thread.sleep(100);
new ThreadSafe("longquan").start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static int getNum() {
return num;
}
public static void setNum(int num) {
ThreadSafe.num = num;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
要把共享变量放入synchronized结构体就可以了,避免多线程同时访问共享对象出错!
还有一种方法叫做同步方法:用synchronized关键字形容方法,程序执行的时候必须等待该同步方法执行完毕才嫩被执行,当某个方法调用同步方法的时候。