java语言的关键字,当它用来修饰一个方法或者一个代码块的时候,能够保证在同一时刻最多只有一个线程执行该段代码。
演示:
package com.demo;public class DemoSynchronized {public static void main(String[] args) {// TODO Auto-generated method stubTest test=new Test();Thread thread=new Thread(test, "ThreadA");Thread thread2=new Thread(test,"ThreadB");thread.start();thread2.start();}}class Test implements Runnable{@Overridepublic void run() {// TODO Auto-generated method stubString threadName=Thread.currentThread().getName();if(threadName.equals("ThreadA")){synchronizedMethod();} else{nonsynchronizedMethod();}}public void synchronizedMethod(){synchronized (this) {for(int i=0;i<5;i++){System.out.println("This is the synchronized method.");try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}public void nonsynchronizedMethod(){for(int i=0;i<5;i++){System.out.println("This is the nonsynchronized method.");try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}
运行结果如下:
This is the synchronized method.This is the nonsynchronized method.This is the synchronized method.This is the nonsynchronized method.This is the nonsynchronized method.This is the synchronized method.This is the synchronized method.This is the nonsynchronized method.This is the synchronized method.This is the nonsynchronized method.
演示:
package com.demo;public class DemoSynchronized {public static void main(String[] args) {// TODO Auto-generated method stubTest test=new Test();Thread thread=new Thread(test, "ThreadA");Thread thread2=new Thread(test,"ThreadB");thread.start();thread2.start();}}class Test implements Runnable{@Overridepublic void run() {// TODO Auto-generated method stubString threadName=Thread.currentThread().getName();if(threadName.equals("ThreadA")){synchronizedMethod();} else{synchronizedMethod2();}}public void synchronizedMethod(){synchronized (this) {for(int i=0;i<5;i++){System.out.println("This is the synchronizedMethod method.");try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}public void synchronizedMethod2(){synchronized (this) {for(int i=0;i<5;i++){System.out.println("This is the synchronizedMethod2 method.");try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}
运行结果如下:
This is the synchronizedMethod method.This is the synchronizedMethod method.This is the synchronizedMethod method.This is the synchronizedMethod method.This is the synchronizedMethod method.This is the synchronizedMethod2 method.This is the synchronizedMethod2 method.This is the synchronizedMethod2 method.This is the synchronizedMethod2 method.This is the synchronizedMethod2 method.新闻热点
疑难解答