多线程并发执行可以提高程序的效率,但是,但多个线程去访问同一个资源的时候,也会引发一些安全问题。
举例说明:
/**
* 测试类
* @author lx
*
*/
public class Test {
public static void main(String[] args) {
//公共类对象
Money money = new Money(10000);
//线程类对象
ExampleThread et1 = new ExampleThread(money, 6000);
ExampleThread et2 = new ExampleThread(money, 6000);
//线程启动
et1.start();
et2.start();
}
}
/**
* 线程类
* @author lx
*
*/
public class ExampleThread extends Thread{
Money money;
int cost;
public ExampleThread(Money money,int cost) {
this.money = money;
this.cost = cost;
}
public void run() {//run 方法
int i = money.getMoney(cost);
if(i == -1){
System.out.println("余额不足,剩余人民币为:" + money.acount );
}
else{
System.out.println("取款成功,取出人民币"+ cost + ",还剩余人民币:" + money.acount);
}
}
}
/**
* 共享类Money
* @author lx
*
*/
public class Money {
int acount;
public Money(int money) {
this.acount = money;
}
public int getMoney(int cost){
if(acount < cost){
return -1;
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
acount -= cost;
return acount;
}
}
从结果可以看出,每跑一次结果都是不同的,要想解决线程安全问题,就必须保证用于处理共享资源的代码块在任何时刻只能有一个线程访问。为了实现这种限制,java提供了同步机制。
举例说明:
package test;
/**
* 测试类
* @author lx
*
*/
public class Test {
public static void main(String[] args) {
Money money = new Money(10000);
ExampleThread et1 = new ExampleThread(money, 6000);
ExampleThread et2 = new ExampleThread(money, 6000);
et1.start();
et2.start();
}
}
/**
* 共享类Money
* @author lx
*
*/
public class Money {
int acount;
public Money(int money) {
this.acount = money;
}
public int getMoney(int cost){
synchronized(this){
if(acount < cost){
return -1;
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
acount -= cost;
}
return acount;
}
}
/**
* 线程类
* @author lx
*
*/
public class ExampleThread extends Thread{
Money money;
int cost;
public ExampleThread(Money money,int cost) {
this.money = money;
this.cost = cost;
}
public void run() {//run 方法
int i = money.getMoney(cost);
if(i == -1){
System.out.println("余额不足,剩余人民币为:" + money.acount );
}
else{
System.out.println("取款成功,取出人民币"+ cost + ",还剩余人民币:" + money.acount);
}
}
}
结果为:
由上述程序结果显示得出,通过同步代码块可以有效的解决多线程的安全问题,当把共享资源的操作放在synchronized 定义的区域内时,便为这些操作加上了同步锁。从而解决了多线程安全问题。