Java 线程同步问题 synchronized

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-- );
		}
	}
	*/
	
}

上一篇:try catch引发的性能优化深度思考


下一篇:【JAVA】笔记(11)--- 精讲异常(附枚举);