1.synchronized(object)
package test.thread;import java.io.IOException;import org.junit.Test;/* * 测试线程锁 */public class TestBlock { public static void main(String[] args) { TestBlock test = new TestBlock(); MyTest thread1 = test.new MyTest(test); thread1.setName("1"); MyTest thread2 = test.new MyTest(test); thread2.setName("2"); thread1.start(); thread2.start(); } /* * 测试同步 */ class MyTest extends Thread{ private Object o; public MyTest(Object o){ this.o=o; } @Override public void run() { // TODO Auto-generated method stub synchronized (o) { //这个o是test对象的实例 ,对类对象实例进行加锁,当线程调用一个实例运行的,另外的线程调用这个实例时候阻塞,达到上锁的目的 try { for(int a=0;a<3;a++){ System.out.println("线程"+MyTest.currentThread().getName()+"修改a=="+a); //MyTest.yield(); } } catch (Exception e) { // TODO: handle exception } } } } }返回的结果: ·
线程1修改a==0
线程1修改a==1
线程1修改a==2
线程1修改a==3
线程1修改a==4
线程1修改a==5
线程1修改a==6
线程1修改a==7
线程1修改a==8
线程1修改a==9
线程2修改a==0
线程2修改a==1
线程2修改a==2
线程2修改a==3
线程2修改a==4
线程2修改a==5
线程2修改a==6
线程2修改a==7
线程2修改a==8
线程2修改a==9
可以看到当一个线程运行完毕之后才运行第二个线程
2.synchronized(this)
package test.thread;import java.io.IOException;import org.junit.Test;/* * 测试线程锁 */public class TestBlock { //调用类 public static void main(String[] args) { TestBlock test = new TestBlock(); MyTest thread1 = test.new MyTest(test); thread1.setName("1"); MyTest thread2 = test.new MyTest(test); thread2.setName("2"); thread1.start(); thread2.start(); } /* * 测试同步 */ class MyTest extends Thread{ private Object o; public MyTest(Object o){ this.o=o; } @Override public void run() { // TODO Auto-generated method stub synchronized (this) { //this 指代当时类 也就是MyTest,两个线程同时调用同一个类方法。就是两个线程对两个实例的各自上锁。互相不阻塞
try { for(int a=0;a<10;a++){ System.out.println("线程"+MyTest.currentThread().getName()+"修改a=="+a); //MyTest.yield(); } } catch (Exception e) { // TODO: handle exception } } } } }返回的结果:
线程1修改a==0
线程1修改a==1
线程1修改a==2
线程1修改a==3
线程1修改a==4
线程2修改a==0
线程1修改a==5
线程1修改a==6
线程1修改a==7
线程1修改a==8
线程1修改a==9
线程2修改a==1
线程2修改a==2
线程2修改a==3
线程2修改a==4
线程2修改a==5
线程2修改a==6
线程2修改a==7
线程2修改a==8
线程2修改a==9