代码如下:
package com.chnsys.thread1;public class JavaResearch01 {public static void main(String[] args) {Ticket t = new Ticket();Thread t1 = new Thread(t);Thread t2 = new Thread(t);/*Thread t3 = new Thread(t);Thread t4 = new Thread(t);*/t1.start();try {Thread.currentThread().sleep(10);} catch (InterruptedException e) {// TODO Auto-generated catch block e.printStackTrace();}t.flag = false;t2.start();/*t3.start();t4.start();*/}}class Ticket implements Runnable{private int tick = 100;Object obj = new Object();boolean flag = true;@Override public void run() {// TODO Auto-generated method stubif(flag){while(true){//同步代码块synchronized (this) {if(tick>0){try {Thread.sleep(100);} catch (Exception e) {// TODO: handle exception }System.out.println(Thread.currentThread().getName()+".....code : "+tick--);}}}}//show()函数while(true){show();}}public synchronized void show(){if(tick>0){try {Thread.sleep(100);} catch (Exception e){//TODO: handle exception }System.out.println(Thread.currentThread().getName()+"....show : "+tick--);}}}