你的位置:首页 > 信息动态 > 新闻中心
信息动态
联系我们

Java 线程同步问题 synchronized

2021-11-21 15:22:03
package com.threadlifetime.ljb;
/**
 * 线程同步问题
 * 1.使用synchronized解决(两种方法)
 *
 */
public class Threadsynch {
	public static void main(String[] args) {
		MyThread0 my = new MyThread0();
		Thread t1 = new Thread(my);
		t1.start();
		
		Thread t2 = new Thread(my);
		t2.start();
		
		Thread t3 = new Thread(my);
		t3.start();
	}
}
class MyThread0 implements Runnable{
	private int ticket = 5;
	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			//解决线程同步问题第一种
			synchronized (this) {
				if(ticket>0) {
					try {
						Thread.sleep(300);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("buy ticket:ticket = " + ticket-- );
				}
			
			}

		}
		
	}
	/**
	//第二种解决办法
	public void run() {
		for (int i = 0; i < 100; i++) {
			sale();
		}
	}
	synchronized public void sale() {
		if(ticket>0) {
			try {
				Thread.sleep(300);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("buy ticket:ticket = " + ticket-- );
		}
	}
	*/
	
}