Static synchronized Method (一)

2014-11-24 09:49:30 · 作者: · 浏览: 2

Java提供了synchronized关键字用于修饰方法,使用synchronized修饰的方法被称为同步方法。当然,synchronized关键字除了修饰方法之外,还可以修饰普通代码块,使用synchronized修饰的代码块被称为同步代码块。

Java语法规定,任何线程进入同步方法,同步代码块之前,必须先获取同步方法,同步代码块对应的同步监控器。

对于同步代码块而言,程序必须显式为它指定同步监视器;对于同步非静态方法而言,该方法的同步监视器是this 即调用该方法的Java对象;对于静态的同步方法而言,该方法的同步监视器不是this,而是该类本身。

public class SynchronizedStatic implements Runnable{

static boolean staticFlag = true;

public static synchronized void test0(){

for(int i=0;i<100;i++){

System.out.println("test0:"+Thread.currentThread().getName()+""+i);

}

}

public void test1(){

synchronized(this){

for(int i=0;i<100;i++){

System.out.println("test1:"+Thread.currentThread().getName()+""+i);

}

}

}

@Override

public void run() {

// TODO Auto-generated method stub

if(staticFlag){

staticFlag=false;

test0();

}else{

staticFlag=true;

test1();

}

}

public static void main(String[] args) throws Exception{

SynchronizedStatic ss = new SynchronizedStatic();

new Thread(ss).start();

//Thread.sleep(10);

new Thread(ss).start();

}

}

test0:Thread-00

test1:Thread-10

test1:Thread-11

test1:Thread-12

test1:Thread-13

test1:Thread-14

test1:Thread-15

test0:Thread-01

test0:Thread-02

test1:Thread-16

test0:Thread-03

test1:Thread-17

test1:Thread-18

test0:Thread-04

test1:Thread-19

test0:Thread-05

test1:Thread-110

test0:Thread-06

test1:Thread-111

test0:Thread-07

test1:Thread-112

test0:Thread-08

test0:Thread-09

test1:Thread-113

test0:Thread-010

test1:Thread-114

test0:Thread-011

test1:Thread-115

test0:Thread-012

test1:Thread-116

test0:Thread-013

test1:Thread-117

test0:Thread-014

test1:Thread-118

test0:Thread-015

test1:Thread-119

test0:Thread-016

test1:Thread-120

test0:Thread-017

test0:Thread-018

test1:Thread-121

test1:Thread-122

test0:Thread-019

test1:Thread-123

test0:Thread-020

test1:Thread-124

test0:Thread-021

test1:Thread-125

test0:Thread-022

test1:Thread-126

test0:Thread-023

test1:Thread-127

test0:Thread-024

test1:Thread-128

test1:Thread-129

test0:Thread-025

test1:Thread-130

test0:Thread-026

test1:Thread-131

test1:Thread-132

test0:Thread-027

test0:Thread-028

test1:Thread-133

test1:Thread-134

test0:Thread-029

test1:Thread-135

test1:Thread-136

test0:Thread-030

test1:Thread-137

test0:Thread-031

test1:Thread-138

test0:Thread-032

test1:Thread-139

test0:Thread-033

test1:Thread-140

test0:Thread-034

test1:Thread-141

test1:Thread-142

test1:Thread-143

test1:Thread-144

test1:Thread-145

test1:Thread-146

test1:Thread-147

test0:Thread-035

test1:Thread-148

test1:Thread-149

test1:Thread-150

test1:Thread-151

test1:Thread-152

test1:Thread-153

test1:Thread-154

test1:Thread-155

test1:Thread-156

test1:Thread-157

test1:Thread-158

test1:Thread-159

test1:Thread-160

test1:Thread-161

test1:Thread-162

test1:Thread-163

test1:Thread-164

test1:Thread-165

test1:Thread-166

test1:Thread-167

test0:Thread-036

test1:Thread-168

test0:Thread-0