多线程实例
多线程案例
一个模拟的买票系统,使用num表示车票的数量:
1 public class TicketCounter implements Runnable{ 2 private int num = 5; 3 @Override 4 public void run() { 5 //因为while(true)所以可以多次执行直到num = 0; 6 while(true){ 7 if(num > 0){ 8 System.out.println(Thread.currentThread().getName() + ":" + num--); 9 } 10 } 11 12 } 13 14 public static void main(String[] args) { 15 /** 16 * 使用通过一个target,可以共享资源 17 */ 18 TicketCounter counter = new TicketCounter(); 19 new Thread(counter, "1号").start(); 20 new Thread(counter, "2号").start(); 21 new Thread(counter, "3号").start(); 22 } 23 24 }
运行结果:
使用Thread.sleep()进行延时:
1 public class TicketCounter2 implements Runnable{ 2 private int num = 5; 3 4 @Override 5 public void run() { 6 7 while(true){ 8 9 if(num > 0){ 10 try { 11 Thread.sleep(1000); 12 } catch (InterruptedException e) { 13 e.printStackTrace(); 14 } 15 System.out.println(Thread.currentThread().getName() + ":" + num--); 16 } 17 } 18 } 19 20 public static void main(String[] args) { 21 TicketCounter2 counter = new TicketCounter2(); 22 new Thread(counter, "1号").start(); 23 new Thread(counter, "2号").start(); 24 new Thread(counter, "3号").start(); 25 } 26 }
运行结果:
通过上述结果发现这个系统出现负数,明显得看出运行错误。
如果想解决这种问题,就需要使用同步。所谓同步就是在统一时间段中只有有一个线程运行,
其他的线程必须等到这个线程结束之后才能继续执行。
同步
同步方法1:
【同步代码块】:
语法格式:
synchronized(同步对象){
//需要同步的代码
}
public class TicketCounter2 implements Runnable{ private int num = 5; @Override public void run() { while(true){ synchronized (this) { if(num > 0){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ":" + num--); } } } } public static void main(String[] args) { TicketCounter2 counter = new TicketCounter2(); new Thread(counter, "1号").start(); new Thread(counter, "2号").start(); new Thread(counter, "3号").start(); } }
运行结果:
同步方法2:采用同步方法。
public class TicketCounter2 implements Runnable{ private int num = 5; @Override public void run() { while(true){ sale(); } } public synchronized void sale(){ if(num > 0){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ":" + num--); } } public static void main(String[] args) { TicketCounter2 counter = new TicketCounter2(); new Thread(counter, "1号").start(); new Thread(counter, "2号").start(); new Thread(counter, "3号").start(); } }
运行结果:
本文引用:资讯《Java多线程总结》,一起来围观吧
http://ms.csdn.net/geek/238191