java多线程之 ---- 线程同步

java多线程之线程同步


线程同步

定义:同步是指在同一时间段内只能运行一个线程。

分类:同步方法同步块。

作用:安全解决共享问题。


同步块:
语法:

synchronized (同步对象) {
需要同步的代码;
}


例子:

public class ThreadDemo implements Runnable{
		
			private int ticket = 5;

			public void run(){
			for(int i=1;i<=5;i++){
				synchronized (this){
					if(ticket>0)
					{
						  Thread.sleep(1000);
						  System.out.println("卖票:ticket="+ticket--);
					}
				}
             }
	}


同步方法:

语法:

synchronized  方法返回值  方法名称 (参数列表) {
}


例子:

public class ThreadDemo implements Runnable{
				private int ticket = 5;
				public void run(){
					for(int i=1;i<=5;i++)
					{
						this.saleTicket();
					}
				}
				public synchronized void saleTicket() {
				if(ticket>0)
				{
					Thread.sleep(1000);	
					System.out.println("卖票:ticket="+ticket--);
				}
			}



同步方法完整示例:

public class Timer {   
    private static int num = 0;   
    public synchronized  void add(String name) { //在执行这个方法过程中,当前对象被锁定   
        num ++;   
        try {   
            Thread.sleep(1);   
        } catch (InterruptedException e) {   
            // TODO Auto-generated catch block   
            e.printStackTrace();   
        }   
        System.out.println(name + " 你是第"+num + "个使用Timer的线程");   
    }   
}   
  
public class TestSync implements Runnable{   

    Timer timer = new Timer();   

    public static void main(String[] args) {   
        TestSync testSync = new TestSync();   
           
        Thread t1 = new Thread(testSync);   
        Thread t2 = new Thread(testSync);   
        t1.setName("t1");   
        t2.setName("t2");   
        t1.start();   
        t2.start();   
    }   

    public void run() {   
        timer.add(Thread.currentThread().getName());   
           
    }   
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值