java 两个线程按顺序输出字符
方法一:
public class threadDemo { public static void main(String[] args) { final Object o=new Object(); final char[] nums="1234567".toCharArray(); final char[] chars="ABCDEFG".toCharArray(); new Thread(new Runnable() { @SneakyThrows @Override public void run() { synchronized (o){ for(char num:nums){ System.out.println(num); o.notify(); o.wait(); } o.notify(); } } }).start(); new Thread(new Runnable() { @SneakyThrows @Override public void run() { synchronized (o){ for(char ch:chars){ System.out.println(ch); o.notify(); o.wait(); } o.notify(); } } }).start(); } }
方法二:
public class threadDemo { static Thread t1=null,t2=null; public static void main(String[] args) { final char[] nums="1234567".toCharArray(); final char[] chars="ABCDEFG".toCharArray(); t1=new Thread(new Runnable() { @Override public void run() { for(char num:nums){ System.out.println(num); LockSupport.unpark(t2); LockSupport.park(); } } }); t2=new Thread(new Runnable() { @Override public void run() { for(char num:chars){ LockSupport.park();//挂起 System.out.println(num); LockSupport.unpark(t1);//叫醒 } } }); t1.start(); t2.start(); } }
方法三:
public class threadDemo {
public static void main(String[] args) {
final char[] nums="1234567".toCharArray();
final char[] chars="ABCDEFG".toCharArray();
final Lock reentrantLock = new ReentrantLock();
final Condition condition = reentrantLock.newCondition();
new Thread(new Runnable() {
@Override
public void run() {
reentrantLock.lock();//相当synchronized
for(char num:nums){
System.out.println(num);
condition.signal();//相当于notify
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
condition.signal();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
reentrantLock.lock();
for(char num:chars){
System.out.println(num);
try {
condition.signal();
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
condition.signal();
}
}).start();
}
}