多线程

demo1:

public class N03_Thread1 implements Runnable//线程任务要实现这个接口
{
	Object o = new Object();
	private int Num = 10;//Num相当于临界资源
	public void run()
	{
		//整个while循环相当于一个临界区所以需要一个同步代码块使得各个线程互斥的进  入临界区
		synchronized (o)//这个同步代码块需要传一个对象,对象随意,也可以用            this。因为同步函数的
		//锁都是this,而同步代码块的锁可以是任意的。静态同步函数的锁则是this.getClass()
		//或者写成:当前类名.class
		{
			while(Num > 0)
			{
				//try {Thread.sleep(10);}catch(InterruptedException e){}
			    System.out.println(Thread.currentThread().getName()+"..."+Num--);
			}			
		}		
	}
}
public class N03_ThreadDemo
{
	public static void main(String[] args) 
	{	
		//模拟买票,n1是普通票,n2是高铁票,即定义了两个线程任务n1和n2
		N03_Thread1 n1 = new N03_Thread1();
		N03_Thread1 n2 = new N03_Thread1();
		//模拟站台t1和t2卖n1票,站台t3和t4卖n2票,即定义了4个线程,线程t1和t2完成线程任务n1
		//线程t2和t3完成线程任务n2
		Thread t1 = new Thread(n1);
		Thread t2 = new Thread(n1);
		Thread t3 = new Thread(n2);
		Thread t4 = new Thread(n2);
		
		t1.start();
		t2.start();
		t3.start();
		t4.start();	
	}
}

demo2:

public class N04_bank 
{
	private int sum;
	
	public synchronized void add()//定义一个同步方法因为这个方法要访问临街资源sum
	//所以本方法即为临界区,并且这个方法要在cus类中的线程任务中调用
    //同步方法的锁为this
	{
		sum = sum + 100;
		System.out.println("sum = "+sum);
	}
}
public class N04_Cus implements Runnable
{
	N04_bank b = new N04_bank();
	public void run()
	{	
		for(int i = 0;i < 3;i++)
		{
			b.add();
		}	
	}
}
//需求:两个客户每次向银行存100元,均共存款三次
public class N04_ThreadDemo
{
	public static void main(String[] args)
	{
		N04_Cus c = new N04_Cus();
		
		Thread t1 = new Thread(c);
		Thread t2 = new Thread(c);
		
		t1.start();
		t2.start();
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值