我们根据以下例子来了解一下线程同步
首先我们来创建一个Pinter类
public class Pinter { public void print1(){
//线程同步锁 synchronized (this) { System.out.print("位"); System.out.print("高"); System.out.print("权"); System.out.print("重"); System.out.println(); } } public void print2(){
//线程同步锁 synchronized (this) { System.out.print("谋"); System.out.print("事"); System.out.print("在"); System.out.print("天"); System.out.println(); } } }
接下来我们来用两个类来操作一下(MyTread1, MyThread2)
public class MyThread1 extends Thread{ public static Pinter print; @Override public void run(){ for(int i=1; i<=500; i++){ print.print1(); } } }
public class MyThread2 implements Runnable { public static Pinter print; @Override public void run() { // TODO Auto-generated method stub for (int i = 0; i <=500; i++) { print.print2(); } } }
我们用实现类来实现一下
public class Text { public static void main(String[] args) { Pinter p = new Pinter(); MyThread1 m = new MyThread1(); m.print=p; m.start(); MyThread2 m1 = new MyThread2(); m1.print=p; Thread t = new Thread(m1); t.start(); } }
效果图展示