1.首先要知道创建线程的方式
(1)通过继承Thread类的方式
(2)通过实现runnable的方式
2.多个线程(多个窗口)卖票这里要考虑线程安全问题,不然会出现错票和重票的问题。这里有上面两种方式实现
(1)通过继承thread类实现
public class CreateThread extends Thread{ static int ticket = 100; boolean isFlag = true; public void run(){ while(isFlag){ show(); } } public synchronized void show(){ synchronized (CreateThread.class) { if(ticket>0){ System.out.println(currentThread().getName()+ticket); ticket--; }else{ isFlag=false; } } } public static void main(String[] args) { CreateThread t1 = new CreateThread(); t1.start(); CreateThread t2 = new CreateThread(); t2.start(); CreateThread t3 = new CreateThread(); t3.start(); } }
这里要非常注意如果使用同步代码块,这个同步监视器的对象,如果是继承方式实现的,那么就要使用CreateThread.class.
(2)通过实现Runnable的方式实现,使用同步代码块,这个同步监视器可以直接使用this.因为实现runnable接口的实现类的对象只有一个,可以实现同步机制。
public class CreateThreadII implements Runnable{ static int ticket =100; @Override public void run() { while(true){ synchronized (this){ if(ticket>0){ System.out.println(Thread.currentThread().getName()+"======>"+ticket); ticket--; } } } } public static void main(String[] args) { CreateThreadII createThreadII = new CreateThreadII(); Thread t1 = new Thread(createThreadII); t1.start(); Thread t2 = new Thread(createThreadII); t2.start(); Thread t3 = new Thread(createThreadII); t3.start(); } }