多线程同步案列

当一个线程进入一个对象的synchronize方法后,其他线程同样可以访问该对象的非synchronize的方法

代码如下

class Test1 {
    public synchronized void synchronizedMethod() {
	 System.out.println("我是第一个线程1");
	 System.out.println("我是第一个线程2");
	 System.out.println("我是第一个线程3");
	 System.out.println("我是第一个线程4");
	try {
	    Thread.sleep(10000);//线程休眠10s
	} catch (InterruptedException e) {
	    System.out.println(e.getMessage());
	}
	System.out.println("结束synchronize方法");
    }

    public void generalMethod() {
	System.out.println("我是第一个线程11");
	System.out.println("我是第一个线程12");
	System.out.println("我是第一个线程13");
	System.out.println("我是第一个线程14");
	
    }
}

public class MutiThread {
    static final Test1 t = new Test1();

    public static void main(String[] args) {
	Thread t1 = new Thread() {
	    public void run() {
		t.synchronizedMethod();
	    }

	};
	Thread t2 = new Thread() {
	    public void run() {
		t.generalMethod();
	    }
	};
	t2.start();
	t1.start();
	
    }
}

运行结果:


同样可以从结果可以看出,两个线程是同时运行的。

猜你喜欢

转载自blog.csdn.net/lsj741223/article/details/80436665