java的线程一直是一个让初学者一个头疼不已的问题,反正是当初可能学习的时候比较烦躁,线程这一部分一直没有了解过他的具体概念和用处,参加工作后才学习的这一块相关的知识,呵呵,下面不多少废话了,说正题。
提到java多线程,难免会想到同步。线程的同步是保证多线程安全访问竞争资源的一种手段。
第一:
说到同步,为什么要对多线程访问的方法限制同步?
很明显,当然是为了避免多个线程统一操作一个数据对象时,对这个数据对象造成破坏。从而造成数据的混乱。这是不允许的。
第二:
那要怎么做,才能做一次只能让一个线程进行操作,操作完后再允许其他线程依次进行操作呢?
在这里不可避免的让我们会想到synchronized关键字
说到synchronized大家要注意一点,他只能标记非抽象的方法。
在java里面首先我们要把需要统一操作一个数据的对象资源设置为private ,限制不能直接访问。
再而就是用synchronized修饰修改变量的方法或代码
以下是我学习时写的测试代码:分为三个clss UserSource CreateMythread 和一个测试的主方法类SynchronizedTest
public class UserSource {
private int num; //封装操作对象
UserSource(int num){
this.num=num;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
/**
*业务逻辑操作
* synchronized同步关键字,限制一次仅有一个线程对本方法进行访问(去掉后打印可以看看多线程对数据争抢操作结果)
* */
public synchronized void chengenum(int fix){
try {
this.num+=fix;
System.out.println(Thread.currentThread().getName()+"操作后"+" 操作动作: num增加"+"“"+fix+"”"+" 当前数量:"+num);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class CreateMythread extends Thread {
private UserSource us;
private int fix=0;
CreateMythread(String name,UserSource us,int fix){
super(name);
this.us=us;
this.fix=fix;
}
public void run() {
us.chengenum(fix);
}
}
public class SynchronizedTest {
public static void main(String[] args) {
UserSource us=new UserSource(100);
CreateMythread a=new CreateMythread("线程1",us,30);
CreateMythread b=new CreateMythread("线程2",us,20);
CreateMythread c=new CreateMythread("线程3",us,-15);
a.start();
b.start();
c.start();
}
}
运行控制台打印结果如下:
线程1操作后 操作动作: num增加“30” 当前数量:130
线程2操作后 操作动作: num增加“20” 当前数量:150
线程3操作后 操作动作: num增加“-15” 当前数量:135