1、synchronized为互斥。该关键词可以申明方法也可以申明代码库。
import java.util.concurrent.TimeUnit; public class SynchronizedDemo1 { public synchronized static void synchronizedDemo(){ try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("test1"); } public static void test1(){ Thread thread = new Thread(){ public void run() { synchronizedDemo(); } }; thread.start(); } public static void test2(){ Thread thread = new Thread(){ public void run() { synchronizedDemo(); } }; thread.start(); } public static void main(String[] args) { SynchronizedDemo1 sd = new SynchronizedDemo1(); sd.test1(); SynchronizedDemo1 sd1 = new SynchronizedDemo1(); sd1.test2(); } }
该类中main为一个线程,分别调用同一个方法。结果得到的互斥的效果,必须要等待前一个方法执行完毕,才能执行后面的调用。经过测试,只要是不同的线程,都会起到互斥的效果
2、下面再看一个例子没有static来修饰的,这里同一对象多个线程都能启动互斥的效果,如果是不同的对象就不能起到互斥的效果。
import java.util.concurrent.TimeUnit; public class SynchronizedDemo2 { public synchronized void synchronizedDemo(){ try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("test1"); } public void test1(){ Thread thread = new Thread(){ public void run() { synchronizedDemo(); } }; thread.start(); } public void test2(){ Thread thread = new Thread(){ public void run() { synchronizedDemo(); } }; thread.start(); } public static void main(String[] args) { SynchronizedDemo2 sd = new SynchronizedDemo2(); sd.test1(); SynchronizedDemo2 sd1 = new SynchronizedDemo2(); sd1.test2(); } }
3、将synchronized修饰在i代码块中。这里的效果和前面类似,只是将synchronized放在代码块中更加灵活。
public class SynchronizedDemo3 { public void synchronizedDemo(){ System.out.println("进入方法:1"); synchronized(this) { try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("等待后:2"); } System.out.println("结束后:3"); } public void test1(){ Thread thread = new Thread(){ public void run() { synchronizedDemo(); } }; thread.start(); } public void test2(){ Thread thread = new Thread(){ public void run() { synchronizedDemo(); } }; thread.start(); } public static void main(String[] args) { SynchronizedDemo3 sd = new SynchronizedDemo3(); sd.test1(); //SynchronizedDemo3 sd1 = new SynchronizedDemo3(); sd.test2(); } }
<p>结果如下</p><p>进入方法:1</p><p>进入方法:1</p><p>等待后:2</p><p>结束后:3</p><p>等待后:2</p><p>结束后:3</p>
时间: 2024-10-13 02:06:17