标签:
//继承Thread public class MyHread1 extends Thread { public Print p1; @Override public void run() { //循环打印print1中的内容 for (int i = 1; i <= 5; i++) { p1.print1(); } } }
public class MyThread2 implements Runnable{ public Print p1; @Override public void run() { //循环输出print2中的内容 for (int i = 1; i <= 5; i++) { p1.print2(); } } }
定义两个类 一个继承Thread 另一个实现Runable 循环输出内容 分别在void前加上锁synchronized
public class Print { public synchronized void print1(){ System.out.print("我"); System.out.print("是"); System.out.println(); } public synchronized void print2(){ System.out.print("好"); System.out.print("人"); System.out.println(); } }
定义一个print类 类中有两个方法 分别输出内容 并且内容之间不换行 直至全部结束再换行
public class Test { public static void main(String[] args) { MyHread1 mh=new MyHread1(); Print p=new Print(); mh.p1=p; mh.start(); MyThread2 mh2=new MyThread2(); mh2.p1=p; Thread th=new Thread(mh2); th.start(); } }
标签:
原文地址:http://www.cnblogs.com/hero96/p/5770608.html