//1.创建线程的对象 test2 t1 = new test2(); test2 t2 = new test2(); test2 t3 = new test2(); //起名字 t1.setName("窗口1"); t2.setName("窗口2"); t3.setName("窗口3"); //开启线程 t1.start(); t2.start(); t3.start();
javaben
public class test2 extends Thread { //被该类所有对象共享 static int ticket = 0; //锁对象,一定是唯一的 static Object lock = new Object(); @Override public void run() { while (true) { synchronized (lock) { if (ticket < 100) { try { Thread.sleep(10); } catch (InterruptedException e) { throw new RuntimeException(e); } ticket++; System.out.println(getName()+"在卖第" + ticket + "张票!!!"); } else { break; } } } } }