Thread 同步线程(打印机同步)

1、首先创建一个打印机对象

package cn.b.happy;

public class Printer {
	Object o =new Object();
	public void print(){
		synchronized(o){
		System.out.print("微");
		System.out.print("冷");
		System.out.print("的");
		System.out.print("雨");
		System.out.println();
		}
	}
	
	public void print1(){
		synchronized(o){
			System.out.print("好");
			System.out.print("人");
			System.out.println();
		}
		
	}

}

  

2、创建两个线程分别为thread1 和 thread2 分别继承thread 和 是实现 runnable接口 包含 打印机 printer 对象

 

package cn.b.happy;

public class MyThread1 extends Thread{

    public Printer print;
    @Override
    public void run() {
        for (int i = 1; i <=500; i++) {
            print.print();
        }
    }
}

 

package cn.b.happy;

public class MyThread2 implements Runnable {
    public Printer print;
    @Override
    public void run() {
        for (int i = 1; i <=500; i++) {
            print.print1();
        }
        
    }

}

 

 3、测试类  实现runnable 接口的 线程 不能调用start()方法,所以创建一个Thread线程对象里边传实现runnable接口的类,从而实现开启线程

package cn.b.happy;

public class Test {
    public static void main(String[] args) {
        Printer p =new Printer();
        MyThread1 t1 =new MyThread1();
        t1.print=p;
        t1.start();
        
        MyThread2 t2 =new MyThread2();
        t2.print=p;
        Thread t=new Thread(t2);
        t.start();
    }
    
    

}

 

转载于:https://www.cnblogs.com/myhome-1/p/5769597.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值