线程同步

线程同步

同步方法synchronized

synchronized

public class Ticket  {
//多个线程同时操作一个对象,数据出错,这样是不安全的

	public static void main(String[] args) throws InterruptedException {
		Ticket1  ticket=new Ticket1();

		Thread thread1=new Thread(ticket,"张三");
		Thread thread2=new Thread(ticket,"李四");
		Thread thread3=new Thread(ticket,"黄牛");

		
		thread3.setPriority(Thread.MIN_PRIORITY);
		

		thread3.start();
		
		thread1.setPriority(5);

		thread1.start();
		
		thread2.setPriority(9);

		thread2.start();

	}

}
class  Ticket1 implements  Runnable{
	private int ticketNum=10;
	
	public synchronized void run() {//加了同步方法 关键字synchronized 这是安全的
		while(true){
			
			if(ticketNum<1){
				
				break;
			}
			System.out.println(Thread.currentThread().getName()+"抢到了第"+ticketNum+"张票");
			ticketNum--;
			}
		}
	}

同步代码快

synchronized (this) {}

public class OutCash {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
          Account account=new Account(10000, "学费");
          Drawing you=new Drawing(account, 600, "你");
          Drawing brother=new Drawing(account, 500, "兄弟");
          you.start();
          brother.start();
	}

}
class Account {
	
	int    money;//卡里有多少钱
	String name;//谁取钱
	public Account(int    money,String name) {
		
		this.money=money;
		this.name=name;
		
	}
}
class Drawing extends Thread{
	
	Account account;
	int Drawmoney;//取多少钱
	int Nowmoney;//拿在手里多少钱
	
	
	public Drawing(Account account,int Drawmoney,String name){
		super(name);
		this.account=account;
		this.Drawmoney=Drawmoney;
		
		
	}
    public void run(){//取钱
    	
    	
    	synchronized (this) {//synchronized 默认锁this
        	//判断账户是否有足够的钱
        	if(account.money<Drawmoney){
        		
        	System.out.println(Thread.currentThread().getName()+"没取到!");
        		return;
        	}
      
        	Nowmoney=Nowmoney+Drawmoney;
        	account.money=account.money-Drawmoney;
        	System.out.println(Thread.currentThread().getName()+"手里的钱:"+Nowmoney);
        	System.out.println(account.name+"还剩:"+account.money);
		}
    }
	
} 

JUC安全集合

import java.util.concurrent.CopyOnWriteArrayList;

public class JUC {
//JUC安全类
	public static void main(String[] args) {
		//CopyOnWriteArrayList提供一个安全的 集合
		CopyOnWriteArrayList<String>list=new CopyOnWriteArrayList<String>();
		
		for (int i = 0; i < 1000; i++) {
               new Thread(()->{
            	   
            	   list.add(Thread.currentThread().getName());
               }).start();;
		} 
		
		
		   System.out.println(list.size());
	}
       
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值