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();
}
}