java 线程之锁技术

package com.thread.synchronizeds;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class CoLockTest {

public static void main(String[] args) {
// TODO 自动生成的方法存根
new CoLockTest().init();
}

private void init() {
final Outputer outputer = new Outputer();
new Thread(new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
outputer.output(“zhangxiaoxiang”);
}
}
}).start();
new Thread(new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
outputer.output(“yuhaomin”);
}
}
}).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();
}
}

 

}
}

    原文作者:java锁
    原文地址: https://www.cnblogs.com/1130136248wlxk/articles/5246823.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞