- class Resourse{
- private String name;//定义资源的属性,名字
- private int count=1;//定义资源属性,编号为
- public synchronized void set(String name){
- this.name=name+count;
- count++;
- System.out.println(Thread.currentThread.setName().getName+"....生产者...."+this.name);
- }
- public synchronized void out(String name){
- System.out.println(Thread.currentThread.setName().getName+"..消费者.."+this.name);
- }
- }
- //描述生产者
- class Producer implements Runnable{
- private Resourse r;
- Producer(Resourse r){
- this.r=r;
- }
- public void run(Resourse r){
- while(true){
- r.set("面包");
- }
- }
-
- }
- //描述消费者
- class Consumer implements Runnable{
- private Resourse r;
- Consumer(Resourse r){
- this.r=r;
- }
- public void run(Resourse r){
- while(true){
- r.out("面包");
- }
- }
- }
- public class ThreadDemo {
- public static void main(String[] args){
- Resourse r=new Resourse();//创建资源对象
-
- Producer pro=new Producer(r);//创建线程任务
- Consumer con=new Consumer(r);
-
-
-
- Thread t1=new Thread(pro);
- Thread t2=new Thread(con);
-
- t1.start();
- t2.start();
-
- }
- }
复制代码 |
|