第一:使用对象lock和unlock控制输出:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class ABC {
private static int state = 0;
public static void main(String[] args) {
final Lock l = new ReentrantLock();
Thread A = new Thread(new Runnable(){
@Override
public void run() {
while (state<=30) {
l.lock();
if(state%3==0){
System.out.println("A");
state ++;
}
l.unlock();
}
}
});
Thread B = new Thread(new Runnable(){
@Override
public void run() {
while (state<=30) {
l.lock();
if(state%3==1){
System.out.println("B");
state ++;
}
l.unlock();
}
}
});
Thread C = new Thread(new Runnable(){
@Override
public void run() {
while (state<=30) {
l.lock();
if(state%3==2){
System.out.println("C");
state ++;
}
l.unlock();
}
}
});
A.start();
B.start();
C.start();
}
}
第二:用synchronized对该资源对象上锁,用notify唤醒占用该资源的线程,用wait()挂起占用该资源的线程
public class TestThread {
public static void main(String[] args) {
String stra = "A";
String strb = "B";
String strc = "C";
TestABC t= new TestABC();
new Thread(){
public void run(){
t.outABC(stra, strb);
}
}.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Thread(){
public void run(){
t.outABC(strb, strc);
}
}.start();
new Thread(){
public void run(){
t.outABC(strc, stra);
}
}.start();
}
}
class TestABC{
public void outABC(String str1,String str2){
while(true){
synchronized (str1) {
System.out.println(str1);
synchronized (str2) {
str2.notify();
}
try{
str1.wait();
Thread.sleep(100);
}catch(Exception e){
System.out.println(e);
}
}
}
}
}
总结:最重要的是明白锁的是什么,不是线程,是资源对象。唤醒的挂起的锁死的都是一个共享资源上的线程,并不能对创建的线程对象进行操作。(迄今。个人理解)