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