package com.cavaness.quartzbook.chapter3;/*** 开始两个线程,一个线程调用同步代码块,另外一个调用同步函数,同步代码块和同步函数的代码一模一样,所以* 同步代码块和同步函数两者之间也必须同步,即是不能存在一个线程调用同步代码块的同时另外一个线程调用同步函数* @author Kevin**/
public class Test {public static void main(String[] args) throws InterruptedException {TestThread testThread = new TestThread();new Thread(testThread).start(); // 此线程调用同步代码块try { // 立即让第一个线程去执行run方法Thread.sleep(1);} catch (InterruptedException e) {e.printStackTrace();throw e;}testThread.setWay("method");new Thread(testThread).start();}
}
package com.cavaness.quartzbook.chapter3;public class TestThread implements Runnable {private static int tickets = 100; // 一百张车票private String way = "";public void setWay(String way) {this.way = way;}/*** tickets是多个线程共享的数据,因此存在线程安全的问题。*/@Overridepublic void run() {if (way.equals("")) { // 执行同步代码块的线程while (true) {synchronized (this) { // 用Runnable创建多线程,多个线程,同个对象,所以此处的this是同一个Runnable对象if (tickets > 0) {try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("run:" + Thread.currentThread().getName() + " is saling " + tickets--);}}}} else {while (true) {sale(); // 执行同步函数的线程}}}private synchronized void sale() {if (tickets > 0) {try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Method run:" + Thread.currentThread().getName()+ " is saling " + tickets--);}}}