public class LockTest {
/**
* @param args
*/
public static void main(String[] args) {
new LockTest().init();
}
private void init(){
final Outputer outputer = new Outputer();//这个家伙一定要找一个外部类,也就是 谁调用了 init()方法。
new Thread(new Runnable(){
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
}catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output("zhangxiaoxiang");
}
}
}).start();
new Thread(new Runnable(){
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
}catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output("lihuoming");
}
}
}).start();
}
static class Outputer {
Lock lock = new ReentrantLock();
public void output(String name) {
int len = name.length();
lock.lock();
try{
for (int i = 0; i < len; i++) {
System.out.print(name.charAt(i));
}
System.out.println();// 此句为 换行。
}finally{
lock.unlock();
}
}
}
}
package com.itm.thread;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockTest {
/**
* @param args
*/
public static void main(String[] args) {
new LockTest().init();
}
private void init(){
final Outputer outputer = new Outputer();//这个家伙一定要找一个外部类,也就是 谁调用了 init()方法。
new Thread(new Runnable(){
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
}catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output("zhangxiaoxiang");
}
}
}).start();
new Thread(new Runnable(){
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
}catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output("lihuoming");
}
}
}).start();
}
static class Outputer {
Lock lock = new ReentrantLock();
public void output(String name) {
int len = name.length();
lock.lock();
try{
for (int i = 0; i < len; i++) {
System.out.print(name.charAt(i));
}
System.out.println();// 此句为 换行。
}finally{
lock.unlock();
}
}
}
}
读写锁:
public interface ReadWriteLock
ReadWriteLock 维护了一对相关的锁,一个用于只读操作,另一个用于写入操作。只要没有 writer,读取锁可以由多个 reader 线程同时保持。写入锁是独占的。