zoukankan      html  css  js  c++  java
  • 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();
        }
        
        
    
    }
  • 相关阅读:
    Python-Image 基本的图像处理操作
    剪枝
    poj1182(食物链)续
    HLG2035广搜
    HLG2040二叉树遍历已知前中,求后
    先序,中序,后序,已知两者求第三者
    C++中new的解说
    僵尸进程
    HLG2062(make,heap问题)
    make_head,,,pop_head,,,push_head,,,sort_head..
  • 原文地址:https://www.cnblogs.com/myhome-1/p/5769597.html
Copyright © 2011-2022 走看看