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

xiaoxiao2021-02-27  151

使用同步方法解决

 格式:

  修饰符 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();

}

}

转载请注明原文地址: https://www.6miu.com/read-16865.html

最新回复(0)