多线程学习笔记(3)同步函数

同步函数使用什么锁?
怎么证明同步函数使用this锁?

两个线程,一个线程使用同步函数,另一个线程使用同步代码块this锁。能够同步吗?
可以。

class TrianThread1 implements Runnable {
	// 总共有一百张火车票
	private int i = 100;
	private Object obj = new Object();
	public Boolean flag = true;

	@Override
	public void run() {

		if (flag) {
			while (i > 0) {
				synchronized (obj) {
					if (i > 0) {
						try {
							
							Thread.sleep(50);
						} catch (Exception e) {
							// TODO: handle exception
						}
						System.out.println(Thread.currentThread().getName() + "出售第" + (100 - i + 1) + "张票");
						i--;
					}
				}
			}

		} else {
			while (i > 0) {
				sale();
			}
		}
	}
	/*
	 * //模拟抢票 while (i > 0 ){ try { Thread.sleep(50); } catch (Exception e) { //
	 * TODO: handle exception } sale(); }
	 */

	public synchronized void sale() {
		// synchronized (obj) {
		if (i > 0) {
			System.out.println(Thread.currentThread().getName() + "出售第" + (100 - i + 1) + "张票");
			i--;
		}
		// }
	}
}

public class ThreadDemo {

	public static void main(String[] args) throws InterruptedException {
		TrianThread1 trianThread1 = new TrianThread1();
		Thread t1 = new Thread(trianThread1, "窗口1");
		Thread t2 = new Thread(trianThread1, "窗口2");
		t1.start();
		Thread.sleep(40);
		trianThread1.flag = false;
		t2.start();
	}
}

猜你喜欢

转载自blog.csdn.net/huermiss/article/details/80267732