线程同步_synchronized

2021-01-04 22:29

阅读:461

标签:getname   线程   java   turn   runnable   nts   str   extends   star   

//数据共享
package
projict05; import java.util.ArrayList; public class test31{ public static void main(String[] args) { TicketSaler t1=new TicketSaler("窗口一"); TicketSaler t2=new TicketSaler("窗口二"); t1.start(); t2.start(); } } class TicketSaler extends Thread{//只能单继承 private static TicketService ts=new TicketService();//静态 public TicketSaler(String name) { super(name); } public synchronized static void saleOneTicket() {//静态 if(ts.hasTicket()) {//用于安全检查 try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+ts.sale()); } } public void run() { while(ts.hasTicket()) { saleOneTicket(); } } } class TicketService { private ArrayList all; public TicketService() { all=new ArrayList(); for(int i=1;i) { all.add("ticket:"+i); } } public boolean hasTicket() { return all.size()>0; } public String sale() { return all.remove(0); } }
package projict06;

import java.util.ArrayList;

public class test32 {
    public static void main(String[] args) {
        MyRun my=new MyRun();
        
        Thread t1=new Thread(my,"窗口一");
        Thread t2=new Thread(my,"窗口二");
        
        t1.start();
        t2.start();
    }
}
class MyRun implements Runnable{//可实现多接口
    private TicketService ts=new TicketService();//非静态
    
    public synchronized  void saleOneTicket() {//非静态
        if(ts.hasTicket()) {//用于安全检查
            try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+ts.sale());
            }
    }
    public void run() {        
        while(ts.hasTicket()) {            
                saleOneTicket();
            }
        }        
    }
class TicketService {
       private ArrayList all;
       
       public TicketService() {
           all=new ArrayList();
           for(int i=1;i) {
               all.add("ticket:"+i);
           }
       }
       
       public boolean hasTicket() {
           return all.size()>0;
       }
       
       public String sale() {
           return all.remove(0);
       }
    }

 

线程同步_synchronized

标签:getname   线程   java   turn   runnable   nts   str   extends   star   

原文地址:https://www.cnblogs.com/hapyygril/p/12983196.html


评论


亲,登录后才可以留言!