线程同步(一)
1 /** 2 * 采用两个线程共享同一个数据对象的方式对同一数据进行操作 3 */ 4 5 package com.starain.threaddemo; 6 public class TongBu { 7 public static void main(String[] args) { 8 Tickets ticket = new Tickets(20); 9 InPut input = new InPut(ticket); 10 OutPut output = new OutPut(ticket); 11 input.start(); 12 output.start(); 13 } 14 } 15 class Tickets{//票类 16 int number;//票编号 17 int size;//票的总数量 18 int i;//出票次数 19 boolean available = true; 20 public Tickets(int size){ 21 this.size = size; 22 } 23 } 24 class InPut extends Thread{ 25 Tickets ticket; 26 public InPut(Tickets ticket){ 27 this.ticket = ticket; 28 } 29 public void run(){ 30 while(ticket.number<ticket.size){ 31 System.out.println("input the"+(++ticket.number)+"ticket"); 32 ticket.available = true; 33 } 34 } 35 } 36 class OutPut extends Thread{ 37 Tickets ticket; 38 public OutPut(Tickets ticket){ 39 this.ticket = ticket; 40 } 41 public void run(){ 42 while(ticket.i<ticket.size){ 43 if(ticket.available==true&&ticket.i<ticket.size){ 44 System.out.println(" output the"+(++ticket.i)+"ticket"); 45 } 46 if(ticket.i==ticket.number){ 47 ticket.available = false; 48 } 49 } 50 } 51 }
解决方法就是用synchronize进行同步
1 /** 2 * 采用两个线程共享同一个数据对象的方式对同一数据进行操作 3 */ 4 5 package com.starain.threaddemo; 6 public class TongBu { 7 public static void main(String[] args) { 8 Tickets ticket = new Tickets(20); 9 InPut input = new InPut(ticket); 10 OutPut output = new OutPut(ticket); 11 input.start(); 12 output.start(); 13 } 14 } 15 class Tickets{//票类 16 int number;//票编号 17 int size;//票的总数量 18 int i;//出票次数 19 boolean available = true; 20 public Tickets(int size){ 21 this.size = size; 22 } 23 } 24 class InPut extends Thread{ 25 Tickets ticket; 26 public InPut(Tickets ticket){ 27 this.ticket = ticket; 28 } 29 public void run(){ 30 synchronized(ticket){ 31 while(ticket.number<ticket.size){ 32 System.out.println("input the"+(++ticket.number)+"ticket"); 33 ticket.available = true; 34 } 35 } 36 } 37 } 38 class OutPut extends Thread{ 39 Tickets ticket; 40 public OutPut(Tickets ticket){ 41 this.ticket = ticket; 42 } 43 public void run(){ 44 while(ticket.i<ticket.size){ 45 46 synchronized(ticket){ 47 48 if(ticket.available==true&&ticket.i<ticket.size){ 49 System.out.println(" output the"+(++ticket.i)+"ticket"); 50 } 51 if(ticket.i==ticket.number){ 52 ticket.available = false; 53 } 54 } 55 56 } 57 } 58 }