方法一:使用继承Thread类实现
public class ThreadDemo extends Thread{ static Object obj = new Object(); //总票数为10张 static int sum = 10; @Override public void run() { while (true){ synchronized (obj){ if (sum>0){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "买了1张票" + ",还剩" + --sum + "张票"); }else { System.out.println(Thread.currentThread().getName() + "票已售完!"); break; } } } } }
public class Test { public static void main(String[] args) { ThreadDemo th1 = new ThreadDemo(); th1.setName("一号窗口:"); th1.start(); ThreadDemo th2 = new ThreadDemo(); th2.setName("二号窗口:"); th2.start(); } }
方法二:实现Runnable接口
public class RunnableDemo implements Runnable{ static int sum = 10; static Object obj = new Object(); @Override public void run() { while(true){ synchronized (this){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } if(sum>0){ System.out.println(Thread.currentThread().getName() + "购买了1张票,还剩" + --sum + "张票"); }else { System.out.println(Thread.currentThread().getName() + "票已售完!"); break; } } } } }
public class Test { public static void main(String[] args) { RunnableDemo runnableDemo = new RunnableDemo(); Thread th1 = new Thread(runnableDemo); Thread th2 = new Thread(runnableDemo); th1.setName("窗口一:"); th2.setName("窗口二:"); th1.start(); th2.start(); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)