package jayxigua.coding.zfb._20180513;
public class MultiThreadPrint {
public final static Integer MAX = 100;
public static int global = 0;
/**
* 问题描述:2个线程A,B(A只能打印单数,B只能打印双数)分别按照整体顺序打印1,2,3,4...99,100
* 技术点:多线程,同步控制,易扩展(例如需要支持3,4个线程时)
* 难度:★★★☆
*
* @author jayxigua
*
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// new Thread(new MyThread(-2, 3)).start();
// new Thread(new MyThread(-1, 3)).start();
// new Thread(new MyThread(0, 3)).start();
new Thread(new MyThread(-1, 2)).start();
new Thread(new MyThread(0, 2)).start();
}
}
class MyThread implements Runnable {
int value;
int offset;
public MyThread(int value, int offset) {
super();
this.value = value;
this.offset = offset;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
@Override
public void run() {
// TODO Auto-generated method stub
while (value + offset <= MultiThreadPrint.MAX) {
// System.out.println("[debug] 线程名 " + Thread.currentThread().getName() + "value
// =" + value + ", global =" + MultiThreadPrint.global);
synchronized (MultiThreadPrint.MAX) {
if (value + offset == MultiThreadPrint.global + 1) {
value = value + offset;
MultiThreadPrint.global = value;
System.out.println("线程名 " + Thread.currentThread().getName() + ",打印值 " + value);
} else {
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
网友评论