本来这节内容是要到后面来说的,因为最近在弄并发的问题,推荐一本书《java并发编程实战》,深入的讲解了多线程问题的。本人最近也刚好在看这本书,还不错的~
多线程的相关概念,就不用说了的,自己可以去网上查找,有一大堆关于它的讲解~
先来看看买票的程序:
package me.javen.thread.one; public class TicketDemo { public static void main(String[] args) { // 使用Thread类的方式 // TicketThead ticketThead1 = new TicketThead(); // TicketThead ticketThead2 = new TicketThead(); // TicketThead ticketThead3 = new TicketThead(); // ticketThead1.start(); // ticketThead2.start(); // ticketThead3.start(); // 使用Runnable的方式 TicketRunnable ticketRunnable = new TicketRunnable(); Thread thread1 = new Thread(ticketRunnable); Thread thread2 = new Thread(ticketRunnable); Thread thread3 = new Thread(ticketRunnable); thread1.run(); thread2.run(); thread3.run(); } } class TicketThead extends Thread { private int ticket = 10; public void run() { for (int i = 0; i < 100; i++) { if (this.ticket > 0) { System.out.println(Thread.currentThread().getName() + "买票:ticket=" + (ticket--)); } } } } class TicketRunnable implements Runnable { private int ticket = 10; @Override public void run() { for (int i = 0; i < 100; i++) { if (this.ticket > 0) { System.out.println(Thread.currentThread().getName() + "买票:ticket=" + (ticket--)); } } } }
【小白的java成长系列】——多线程初识(多人买票问题),布布扣,bubuko.com
原文地址:http://blog.csdn.net/enson16855/article/details/38372239