package com.gzhs.zsd.thread;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
-
Thread线程Lock测试
*/
public class Thread_Lock {public static void main(String[] args) {
//测试
new Thread_Lock().More_Thread1();
}public void More_Thread1(){
final MyPrint1 myPrint = new MyPrint1(); //创建线程1 new Thread(new Runnable() { @Override public void run() { while(true){ try { Thread.sleep(200); myPrint.outprint("xiezepeng"); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); //创建线程2 new Thread(new Runnable() { @Override public void run() { while(true){ try { Thread.sleep(200); myPrint.outprint("xiesuenpeng"); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start();
}
//内部类
class MyPrint1{
//创建一把锁, 该锁应用到同一个对象
Lock lock = new ReentrantLock();
//输出
public void outprint(String name){
//上锁
lock.lock();
try {
for(int i = 0; i < name.length(); i++){
System.out.print(name.charAt(i));
}
System.out.println();
} catch (Exception e) {
e.printStackTrace();
} finally{
//解锁
lock.unlock();
}
}
}
}