多线程之synchronized

java的堆中信息是共享的,线程是把会堆中信息拷贝,对副本进行操作,操作完再同步堆中的信息,而堆中的信息可能被b线程修改了,a线程的副本还是未修改前的,此时就引发多并发问题。解决多并发的问题就是通过枷锁,使原先多个线程并行执行程序转为多个线程串行执行程序。

例;

请编写2个线程,线程1顺序输出1,3,5,……, 99 等奇数,每个数 一 。

线程2顺序输出2,4,6……100等偶数,每个数 一 。

最终的结果要求是输出为 自然顺序:1,2,3,4,……99,100。

public class TestLock2 implements Runnable {
	private int num;

	private int initNum;

	public TestLock2(int num, int initNum) {
		this.num = num;
		this.initNum = initNum;
	}

	@Override
	public void run() {
		synchronized (this) {
			while (initNum < num) {
				this.notify();
				System.out.println(Thread.currentThread().getName() + ":" + initNum);
				initNum++;
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public static void main(String[] args) {
         //打印一百个数,两个线程个循环50次,两个都是用testLock2这个实例构造,testLock2里面的全局变量是共享的 TestLock2 testLock2 = new TestLock2(51, 1); Thread thread1 = new Thread(testLock2); thread1.setName("线程1"); Thread thread2 = new Thread(testLock2); thread2.setName("线程2"); thread1.start(); try { thread1.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } thread2.start(); } }

  

 

猜你喜欢

转载自www.cnblogs.com/thomas-seven/p/9002791.html