java中多线程安全问题产生&解决方案——同步方法


使用同步方法解决

 格式:

  修饰符 synchronized 返回值 方法(){

 

}


package com.itheima_05;
/*
 * 同步方法:使用关键字synchronized修饰的方法,一旦被一个线程访问,则整个方法全部锁住,其他线程则无法访问
 * 
 * synchronized
 * 注意:
 * 		非静态同步方法的锁对象是this
 * 		静态的同步方法的锁对象是当前类的字节码对象
 */
public class TicketThread implements Runnable {
	static int tickets = 100;// 火车票数量
	Object obj = new Object();

	@Override
	public void run() {
		// 出售火车票
		while (true) {
			/*synchronized (obj) {
				method();
			}*/
			
			//method();
			method2();

		}
	}

	private synchronized void method() {
		if (tickets > 0) {
           
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			System.out.println(Thread.currentThread().getName() + ":" + tickets--);
		}
	}
	
	
	private static synchronized void method2() {
	
		if (tickets > 0) {

			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			System.out.println(Thread.currentThread().getName() + ":" + tickets--);
		}
	}

	

}

package com.itheima_05;

 

public class TicktetTest {

public static void main(String[] args) {

//创建线程对象

TicketThread tt = new TicketThread();

Thread t = new Thread(tt);

t.setName("窗口1");

Thread t2 = new Thread(tt);

t2.setName("窗口2");

Thread t3 = new Thread(tt);

t3.setName("窗口3");

//启动线程对象

t.start();

t2.start();

t3.start();

}

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值