当前位置: 代码迷 >> 综合 >> 同步函数
  详细解决方案

同步函数

热度:82   发布时间:2024-01-17 03:15:44.0
package com.cavaness.quartzbook.chapter3;/*** 四个线程在卖100张票* @author Kevin**/
public class Test {public static void main(String[] args) {TestThread testThread = new TestThread();new Thread(testThread).start();new Thread(testThread).start();new Thread(testThread).start();new Thread(testThread).start();}
}
package com.cavaness.quartzbook.chapter3;public class TestThread implements Runnable {private static int tickets = 100; // 一百张车票/*** tickets是多个线程共享的数据,因此存在线程安全的问题。*/@Overridepublic void run() {while (true) {sale();}}public synchronized void sale() {if (tickets > 0) {try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Method run:" + Thread.currentThread().getName() + " is saling " + tickets--);}}}


  相关解决方案