经典案例那个什么多线程--卖票..........................就是好像有点不对~~!先写下来.有大哥哥,大姐姐帮看下吗
2019-11-28

package javawork;

public class RunnableDemo2 {

public static void main(String[] args) {Runnable02 ru = new Runnable02();Thread ru1 = new Thread(ru);Thread ru2 = new Thread(ru);// 两个窗口ru1.start();// 两个窗口启动ru2.start();}

}

 

class Runnable02 implements Runnable {private int num = 16;Object obj = new Object();String s = new String();boolean flag = false;

@Overridepublic void run() {while (true) {// 同步代码块// flag为 false时 执行同步代码块if (!flag) {synchronized (this) {// 同步代码快的函数可以是任意函数if (num > 0) {System.out.println(Thread.currentThread().getName() + ":" + (num--) + "号票" + "同步代码块++++");try {Thread.sleep(100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} // 睡眠0.2S}flag = true;}// 同步函数} else {funtion();flag = false;}

}}

// 同步函数的锁是Thispublic synchronized void funtion() {if (num > 0) {System.out.println(Thread.currentThread().getName() + ":" + (num--) + "号票" + "同步函数----");try {Thread.sleep(100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} // 睡眠0.2S}}}