import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 十一、线程锁
*
* @author dahai
*
*/
public class LockTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
LockTest.init();
}
public static void init() {
Outputer outputer = new Outputer();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outputer.out("ffffffff");
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outputer.out("hhhhhhhhhh");
}
}
}).start();
}
static class Outputer {
Lock lock = new ReentrantLock();
public void out(String str) {
lock.lock();
try {
for (int i = 0; i < str.length(); i++) {
System.out.print(str.charAt(i));
}
} finally {
lock.unlock();
}
}
}
}
import java.util.concurrent.locks.ReentrantLock;
/**
* 十一、线程锁
*
* @author dahai
*
*/
public class LockTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
LockTest.init();
}
public static void init() {
Outputer outputer = new Outputer();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outputer.out("ffffffff");
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outputer.out("hhhhhhhhhh");
}
}
}).start();
}
static class Outputer {
Lock lock = new ReentrantLock();
public void out(String str) {
lock.lock();
try {
for (int i = 0; i < str.length(); i++) {
System.out.print(str.charAt(i));
}
} finally {
lock.unlock();
}
}
}
}