Java 多线程 —— synchronized关键字

时间:2023-03-08 20:16:50
Java 多线程 —— synchronized关键字

java 多线程 目录:

Java 多线程——基础知识

Java 多线程 —— synchronized关键字

java 多线程——一个定时调度的例子

java 多线程——quartz 定时调度的例子

java 多线程—— 线程等待与唤醒

多线程的同步机制对资源进行加锁,使得在同一个时间,只有一个线程可以进行操作,同步用以解决多个线程同时访问时可能出现的问题。

同步机制可以使用synchronized关键字实现。

当synchronized关键字修饰一个方法的时候,该方法叫做同步方法。

当synchronized方法执行完或发生异常时,会自动释放锁。

下面通过一个例子来对synchronized关键字的用法进行解析。

1.是否使用synchronized关键字的不同

 public class test_Thread_1 {

     public static void main(String[] args)
{
Example example = new Example();
Thread t1 = new Thread1(example);
Thread t2 = new Thread1(example);
t1.start();
t2.start();
} }
class Example
{
public synchronized void exec()
{
for(int i=0;i<10;i++){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("hello:"+i);
}
}
} class Thread1 extends Thread
{
private Example example;
public Thread1(Example example){
this.example = example;
} public void run(){
example.exec();
} }

是否在execute()方法前加上synchronized关键字,这个例子程序的执行结果会有很大的不同。

  如果不加synchronized关键字,则两个线程同时执行execute()方法,输出是两组并发的。

  如果加上synchronized关键字,则会先输出一组,然后再输出下一组,说明两个线程是顺次执行的。

2.多个方法的多线程情况

 public class test_Thread_2
{ public static void main(String[] args){
Example1 example = new Example1();
Thread t1 = new Thread3(example);
Thread t2 = new Thread4(example);
t1.start();
t2.start();
} } class Example1
{
public synchronized void exec3()
{
for(int i=0;i<5;i++){
try {
Thread.sleep((long) Math.random() * 1000);
//Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("hello:"+i);
}
} public synchronized void exec4()
{
try {
Thread.sleep((long) Math.random() * 1000);
//Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} for(int i=0;i<5;i++){
System.out.println("world:"+i);
}
}
} class Thread3 extends Thread
{
private Example1 example; public Thread3(Example1 example) {
// TODO Auto-generated constructor stub
this.example = example;
} public void run(){
example.exec3();
}
} class Thread4 extends Thread
{
private Example1 example;
public Thread4(Example1 example) {
// TODO Auto-generated constructor stub
this.example = example;
}
public void run(){
example.exec4();
}
}

如果去掉synchronized关键字,则两个方法并发执行,并没有相互影响。

  但是如例子程序中所写,即便是两个方法:

  执行结果永远是执行完一个线程的输出再执行另一个线程的。  

  说明:

  如果一个对象有多个synchronized方法,某一时刻某个线程已经进入到了某个synchronized方法,那么在该方法没有执行完毕前,其他线程是无法访问该对象的任何synchronized方法的。

  结论:

  当synchronized关键字修饰一个方法的时候,该方法叫做同步方法。

  Java中的每个对象都有一个锁(lock),或者叫做监视器(monitor),当一个线程访问某个对象的synchronized方法时,将该对象上锁,其他任何线程都无法再去访问该对象的synchronized方法了(这里是指所有的同步方法,而不仅仅是同一个方法),直到之前的那个线程执行方法完毕后(或者是抛出了异常),才将该对象的锁释放掉,其他线程才有可能再去访问该对象的synchronized方法。

  注意这时候是给对象上锁,如果是不同的对象,则各个对象之间没有限制关系。

  尝试在代码中构造第二个线程对象时传入一个新的Example对象,则两个线程的执行之间没有什么制约关系。

3.考虑静态的同步方法

  当一个synchronized关键字修饰的方法同时又被static修饰,之前说过,非静态的同步方法会将对象上锁,但是静态方法不属于对象,而是属于类,它会将这个方法所在的类的Class对象上锁

  一个类不管生成多少个对象,它们所对应的是同一个Class对象。

 public class test_Thread_3 {

     public static void main(String[] args)
{
Example2 example = new Example2();
Thread t1 = new Thread5(example);
example = new Example2();
Thread t2 = new Thread6(example);
t1.start();
t2.start(); } } class Example2
{
public static synchronized void exec5()
{
for(int i=0;i<5;i++){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("hello:"+i);
}
} public static synchronized void exec6()
{
for(int i=0;i<5;i++){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("world:"+i);
}
}
} class Thread5 extends Thread
{
private Example2 example;
public Thread5(Example2 example){
this.example = example;
}
public void run(){
example.exec5();
}
} class Thread6 extends Thread
{
private Example2 example;
public Thread6(Example2 example){
this.example = example;
}
public void run(){
example.exec6();
}
}

所以如果是静态方法的情况(exec5()和exec5()都加上static关键字),即便是向两个线程传入不同的Example对象,这两个线程仍然是互相制约的,必须先执行完一个,再执行下一个。

  结论:

  如果某个synchronized方法是static的,那么当线程访问该方法时,它锁的并不是synchronized方法所在的对象,而是synchronized方法所在的类所对应的Class对象。Java中,无论一个类有多少个对象,这些对象会对应唯一一个Class对象,因此当线程分别访问同一个类的两个对象的两个static,synchronized方法时,它们的执行顺序也是顺序的,也就是说一个线程先去执行方法,执行完毕后另一个线程才开始。

4. synchronized块

synchronized块写法:

  synchronized(object)

  { 

  }

  表示线程在执行的时候会将object对象上锁。(注意这个对象可以是任意类的对象,也可以使用this关键字)。

  这样就可以自行规定上锁对象。

 public class test_Thread_4
{
public static void main(String[] args){
Example3 example = new Example3();
Thread t1 = new Thread7(example);
Thread t2 = new Thread8(example);
t1.start();
t2.start();
}
} class Example3
{
private Object object = new Object();
public void exec1(){
synchronized (object)
{
for(int i=0;i<5;i++){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("hello:"+i);
}
}
} public void exec2(){
synchronized (object) {
for(int i=0;i<5;i++){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("world:"+i);
}
}
}
} class Thread7 extends Thread
{
private Example3 example; public Thread7(Example3 example) {
// TODO Auto-generated constructor stub
this.example = example;
} public void run(){
example.exec1();
}
} class Thread8 extends Thread
{
private Example3 example; public Thread8(Example3 example) {
// TODO Auto-generated constructor stub
this.example = example;
} public void run(){
example.exec2();
}
}

例子程序4所达到的效果和例子程序2的效果一样,都是使得两个线程的执行顺序进行,而不是并发进行,当一个线程执行时,将object对象锁住,另一个线程就不能执行对应的块。

  synchronized方法实际上等同于用一个synchronized块包住方法中的所有语句,然后在synchronized块的括号中传入this关键字。当然,如果是静态方法,需要锁定的则是class对象。

  可能一个方法中只有几行代码会涉及到线程同步问题,所以synchronized块比synchronized方法更加细粒度地控制了多个线程的访问,只有synchronized块中的内容不能同时被多个线程所访问,方法中的其他语句仍然可以同时被多个线程所访问(包括synchronized块之前的和之后的)。

注意:被synchronized保护的数据应该是私有的

  结论:

  synchronized方法是一种粗粒度的并发控制,某一时刻,只能有一个线程执行该synchronized方法;

  synchronized块则是一种细粒度的并发控制,只会将块中的代码同步,位于方法内、synchronized块之外的其他代码是可以被多个线程同时访问到的。

5. 示例

子线程循环5次,接着主线程循环10次,接着又回到子线程循环5次, 接着再回到主线程又循环10次,如此循环3次.

 /**
* 子线程循环5次,接着主线程循环10次,接着又回到子线程循环5次, 接着再回到主线程又循环10次,如此循环3次.
* @ClassName: threadComunication
* @Description:
* @author xingle
* @date 2014-4-24 下午7:02:55
*/
public class threadComunication {
private static final int COUNT = 3;//一共循环3次 public static void main(String[] args) { final Business business = new Business(); for (int i = 1; i <= COUNT; i++) {
final int index = i;
new Thread(new Runnable() {
@Override
public void run() {
business.subThrad(index);
}
}).start();
business.mainThread(index);
} } static class Business {
private static final int COUNT_SUB = 5;
private static final int COUNT_MAIN = 10; private boolean dosub = true; public synchronized void subThrad(int index) {
while (!dosub) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int m = 0; m < COUNT_SUB; m++) {
System.out.println("subThread " + m + " of " + index);
}
dosub = false;
notifyAll();
} public synchronized void mainThread(int index) {
while (dosub) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int n = 0; n < COUNT_MAIN; n++) {
System.out.println("mainThread " + n + " of " + index);
}
dosub = true;
notifyAll();
}
}
}

执行结果:

subThread 0 of 1
subThread 1 of 1
subThread 2 of 1
subThread 3 of 1
subThread 4 of 1
mainThread 0 of 1
mainThread 1 of 1
mainThread 2 of 1
mainThread 3 of 1
mainThread 4 of 1
mainThread 5 of 1
mainThread 6 of 1
mainThread 7 of 1
mainThread 8 of 1
mainThread 9 of 1
subThread 0 of 2
subThread 1 of 2
subThread 2 of 2
subThread 3 of 2
subThread 4 of 2
mainThread 0 of 2
mainThread 1 of 2
mainThread 2 of 2
mainThread 3 of 2
mainThread 4 of 2
mainThread 5 of 2
mainThread 6 of 2
mainThread 7 of 2
mainThread 8 of 2
mainThread 9 of 2
subThread 0 of 3
subThread 1 of 3
subThread 2 of 3
subThread 3 of 3
subThread 4 of 3
mainThread 0 of 3
mainThread 1 of 3
mainThread 2 of 3
mainThread 3 of 3
mainThread 4 of 3
mainThread 5 of 3
mainThread 6 of 3
mainThread 7 of 3
mainThread 8 of 3
mainThread 9 of 3


附:

java synchronized详解

http://www.cnblogs.com/GnagWang/archive/2011/02/27/1966606.html