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
}
}
}
原文地址:https://www.cnblogs.com/peng1314/p/10029807.html