jdk1.5以后有了java.util.concurrent包
里面对同步提供了相当多的支持
例如lock atomic以及一些可同步操作的容器
下面给出一个常见的多线程面试题及其对应实现
有三个线程ID分别是A、B、C,请有多线编程实现,在屏幕上循环打印10次ABCABC
采用AtomicInteger来实现这个,
不多说了,上代码,还是相当简单易懂的
可以对concurrent包见一斑。。
- import java.util.concurrent.atomic.AtomicInteger;
-
- public class Print extends Thread{
-
- private AtomicInteger synObj;
- private int count;
- private String s;
- private int flag;
- private int total = 0;
-
- public Print(int count,AtomicInteger atomicInteger,String s,int flag) {
- this.count = count;
- this.synObj = atomicInteger;
- this.s = s;
- this.flag = flag;
- }
- public void run() {
- while(true) {
- synchronized(synObj) {
- if(synObj.intValue()%3 == flag) {
- total++;
- synObj.set(synObj.intValue()+1);
- System.out.println(s);
- synObj.notifyAll();
- if(total == count) {
- break;
- }
- }else {
- try{
- synObj.wait();
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- }
- }
- }
- public static void main(String[]args) throws Exception {
- AtomicInteger synObj = new AtomicInteger(0);
- Print a = new Print(10,synObj,"A",0);
- Print b = new Print(10,synObj,"B",1);
- Print c = new Print(10,synObj,"C",2);
- a.start();
- b.start();
- c.start();
- }
- }
import java.util.concurrent.atomic.AtomicInteger;
public class Print extends Thread{
//专门为同步用的 用integer不行,每次都会新建的
private AtomicInteger synObj;
private int count;
private String s;
private int flag;
private int total = 0;
public Print(int count,AtomicInteger atomicInteger,String s,int flag) {
this.count = count;
this.synObj = atomicInteger;
this.s = s;
this.flag = flag;
}
public void run() {
while(true) {
synchronized(synObj) {
if(synObj.intValue()%3 == flag) {
total++;
synObj.set(synObj.intValue()+1);
System.out.println(s);
synObj.notifyAll();
if(total == count) {
break;
}
}else {
try{
synObj.wait();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
public static void main(String[]args) throws Exception {
AtomicInteger synObj = new AtomicInteger(0);
Print a = new Print(10,synObj,"A",0);
Print b = new Print(10,synObj,"B",1);
Print c = new Print(10,synObj,"C",2);
a.start();
b.start();
c.start();
}
}