- public class ThreadDemo3 implements Runnable {
- private int tickets = 10;
- private boolean flag = true;
-
- @Override
- public void run() {
-
- while(flag){
- test();
- }
-
- }
- public synchronized void test(){
- if(tickets <=0){
- flag = false ;
- return;
- }
-
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName()+"出售了"+tickets--);
- }
- public static void main(String[] args) {
- ThreadDemo3 th = new ThreadDemo3();
- Thread th1 = new Thread(th,"窗口a");
- Thread th2 = new Thread(th,"窗口b");
- Thread th3 = new Thread(th,"窗口c");
- Thread th4 = new Thread(th,"窗口d");
-
- th1.start();
- th2.start();
- th3.start();
- th4.start();
-
- }
-
- }
复制代码
|
|