Java多线程升级篇(一)——synchronized详解
上一周写了两篇关于Java多线程的内容,因为接近七月的最后几天,距离原定的计划还有一段距离,所以要抓紧时间再完成三篇关于java多线程的内容,这个月的总结内容就完成了。Java多线程的内容太多太多,有一些我现在还没有完全的搞明白,自然不敢写博客来误导大家,只是尽自己所能,先学会多少,写多少,也希望大家多多指点。
这一篇是关于Synchronized关键字的,花了一天的时间,内容较多,大家可以慢慢观看,观看时间加编码时间一个下午就可以了。
Synchronized对方法的修饰
上上篇博文其中就谈到了synchronized关键字在程序中的应用,但是,只是简单的提及,足够线程知识的简单的应用,这篇文章会更详细的讲解内容。
Synchronized可以用于访问同一个对象的内容时的线程的顺序执行,但是这里有一个条件,就是对于同一个对象,但是对于不同对象的一个有synchronized的方法时,线程却是会交叉执行的。例如:
public class LoginClass {
private int num=0;
synchronized public void addI(String username) {
try{
if(username.equals("a")) {
num=100;
System.out.println("a set over!");
Thread.sleep(2000);
}else {
num=200;
System.out.println("b set over!");
}
System.out.println(username+" "+num);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
public class Another_thread extends Thread{
private LoginClass numbef;
public Another_thread(LoginClass a) {
this.numbef=a;
}
public void run() {
this.numbef.addI("a");
}
}
public class New_thread extends Thread{
private LoginClass bumref;
public New_thread(LoginClass b) {
this.bumref=b;
}
public void run() {
this.bumref.addI("b");
}
}
public class Test_thread{
public static void main(String[] args){
LoginClass a=new LoginClass();
LoginClass b=new LoginClass();
New_thread athread=new New_thread(a);
athread.start();
Another_thread bthread=new Another_thread(b);
bthread.start();
}
}
结果:
Synchronized是对对象加上锁,而不是对方法加上锁。这样就造成了一个结果,对于一个对象的所有的synchronized的方法,都必须要等待线程的释放以后才能执行,如:
public class LoginClass {
synchronized public void methodA() {
try {
System.out.println(Thread.currentThread().getName());
Thread.sleep(5000);
System.out.println("end"+Thread.currentThread().getName());
}catch(InterruptedException e) {
e.printStackTrace();
}
}
synchronized public void methodB() {
try {
System.out.println(Thread.currentThread().getName()
+" "+System.currentTimeMillis());
Thread.sleep(1000);
System.out.println("end"+Thread.currentThread().getName());
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
public class Another_thread extends Thread{
private LoginClass object;
public Another_thread(LoginClass a) {
this.object=a;
}
public void run() {
this.object.methodB();
}
}
public class New_thread extends Thread{
private LoginClass object;
public New_thread(LoginClass b) {
this.object=b;
}
public void run() {
this.object.methodA();
}
}
public class Test_thread{
public static void main(String[] args){
LoginClass object=new LoginClass();
New_thread a=new New_thread(object);
Another_thread b=new Another_thread(object);
a.setName("a");
b.setName("b");
a.start();
b.start();
}
}