java关于synchronized的某些知识

来源:互联网 发布:淘宝规则虚假交易 编辑:程序博客网 时间:2024/05/17 15:18

说道多线程,就会想到同步的问题,进而就想到synchronized和锁lock,这里不说lock,就只说说synchronized.

synchronized关键字是应用在方法或者一段代码块上面的。意味着如果当前有一个线程正在访问这个方法或者是代码块,那么其他的线程必须等待,知道这个线程访问完。

java在创建对象的时候,都会给每个对象一个钥匙(只有一把万能钥匙),synchronized就相当于是加锁。当访问到一个synchronized方法或者是代码块,使用到了对象的唯一的一把万能钥匙。那么其他的synchronized方法或者是代码块,将会被锁住不能访问,而其他的没有加锁的方法则可以被访问到。

借用个例子来说明:

package com.xaut.cherry.lock0930;


import java.util.Date;


public class SynTest extends Thread{

public static void main(String[] args) {
// TODO Auto-generated method stub
TestMethod method = new TestMethod();
Thread thread1 = new Thread1(method,"t1");
Thread thread2 = new Thread2(method,"t2");
Thread thread3 = new Thread3(method,"t3");
Thread thread4 = new Thread4(method,"t4");
thread1.start();
thread2.start();
thread3.start();
thread4.start();

}


}
class Thread1 extends Thread{
private TestMethod meth1;
public Thread1(TestMethod meth,String name){
setName(name);//设置线程的名字
this.meth1 = meth;
}
public void run(){
super.run();
meth1.Method1();
}
}
class Thread2 extends Thread{
private TestMethod meth2;
public Thread2(TestMethod meth,String name){
setName(name);
this.meth2 = meth;
}
public void run(){
super.run();
meth2.Method2();
}
}
class Thread3 extends Thread{
private TestMethod meth3;
public Thread3(TestMethod meth,String name){
setName(name);
this.meth3 = meth;
}
public void run(){
super.run();
meth3.Method1();
}
}
class  Thread4 extends Thread{
private TestMethod meth4;
public Thread4(TestMethod meth,String name){
setName(name);
this.meth4 = meth;
}
public void run(){
super.run();
meth4.Method3();
}
}
class TestMethod{
public synchronized void Method1(){
System.out.println("this is method1......"+Thread.currentThread().getName()+":"+new Date());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void Method2(){
System.out.println("this is method2......."+Thread.currentThread().getName()+":"+new Date());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void Method3(){
System.out.println("this is method3......."+Thread.currentThread().getName()+":"+new Date());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

-------------------------------------------------------------------------------------

结果:

this is method2.......t2:Sat Sep 30 21:00:48 CST 2017
this is method1......t1:Sat Sep 30 21:00:48 CST 2017
this is method3.......t4:Sat Sep 30 21:00:49 CST 2017
this is method1......t3:Sat Sep 30 21:00:50 CST 2017

多线程问题,先访问那个无所谓,但是注意第一行和第二行是同时进行的,method2是无锁的方法,而method1是有锁的方法。而其他的就相对然言,有一定的延迟,因为代码里面添加了sleep语句。

阅读全文
0 0
原创粉丝点击