标签:
线程同步
package cn.d.happy; public class Printer { Object o=new Object(); //或在void前加synchronized public void print1(){ //同步代码块 synchronized (o){ System.out.print("线"); System.out.print("程"); System.out.print("同"); System.out.print("步"); System.out.println(); } } public void print2(){ synchronized (o){ System.out.print("噢"); System.out.print("呵"); System.out.println(); } } }
定义两个线程类 并重写run方法。继承Thread 和 实现Runnable接口 通过for循环遍历次数
package cn.d.happy; public class MyThread extends Thread{ public Printer print; @Override public void run() { //必须有该类的对象实例 for (int i = 1; i <=10; i++) { print.print1(); } } }
package cn.d.happy; public class MyThread2 implements Runnable{ public Printer print; @Override public void run() { for (int i = 1; i <=10; i++) { print.print2(); } } }
测试类 创建打印机对象 以及两个线程对象并进行赋值
package cn.d.happy; public class Test { public static void main(String[] args) { //购买一个打印机 Printer p=new Printer(); //创建第一个线程对象 并且给属性赋值 MyThread t1=new MyThread(); t1.print=p; t1.start(); //03.创建第二个线程对象 并且给属性赋值 MyThread2 t2=new MyThread2(); t2.print=p; Thread tt=new Thread(t2); tt.start(); } }
实现效果:
标签:
原文地址:http://www.cnblogs.com/jingpeipei/p/5770590.html