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

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;

@Override
public 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 block
e.printStackTrace();
} // 睡眠0.2S
}
flag = true;
}
// 同步函数
} else {
funtion();
flag = false;
}

}
}

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

posted on 2018-11-27 23:33 北九北 阅读() 评论() 编辑 收藏

版权声明:本文为peng1314原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/peng1314/p/10029807.html