多线程编程解决思路
场景一,多个线程要求按照指定的顺序执行, 如现在有A、B、C 3个线程,要求按照A->B->C的顺序来依次执行。
解决思路: A B C 线程需要共享一个标志位,依据标志位来决定A B C是该立即执行还是该阻塞或者是等待或者是让出时间片。
方案1, 用AtomicInteger作为标识位, 用该变量对线程数(3)取模,如果非特定值,则让当前线程让出CPU时间片。否则执行业务逻辑并对标识位进行更新。
public class SeqPrint {
private int n;
public SeqPrint(int n) {
this.n = n;
}
AtomicLong idx = new AtomicLong(0L);
public void foo() throws InterruptedException {
for (int i = 0; i < n; i++) {
while (idx.get() % 2 != 0) {
Thread.yield();
}
System.out.print("foo");
idx.getAndIncrement();
}
}
public void bar() throws InterruptedException {
for (int i = 0; i < n; i++) {
while (idx.get() % 2 == 0) {
Thread.yield();
}
System.out.print("bar");
idx.getAndIncrement();
}
}
public static void main(String[] args) throws InterruptedException {
final SeqPrint seqPrint = new SeqPrint(10);
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
seqPrint.foo();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
seqPrint.bar();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t2.start();
t1.start();
}
}
VGhpcyBpcyBhIHByb2dyYW1taW5nIHRlc3QgYXNzaWdubWVudCBmb3IgY2FuZGlkYXRlcy4NCllvdSBtdXN0IHdvcmsgb24geW91ciBvd24sIGFuZCBzdWJtaXQgeW91ciB3b3JrIHdpdGhpbiAzIGRheXMuIFRoZSB3aG9sZSBzb2x1dGlvbiBtdXN0IGJlIHlvdXIgb3JpZ2luYWwgd29yay4NCklmIHRoZXJlIGlzIGFueXRoaW5nIHVuY2xlYXIgdG8geW91IGFuZCBpcyBub3QgbWVudGlvbmVkIGluIHRoZSBhc3NpZ25tZW50LCB5b3UgY2FuIG1ha2UgeW91ciBvd24gcmVhc29uYWJsZQ0KYXNzdW1wdGlvbiBhbmQgY29tcGxldGUgeW91ciB3b3JrLg0KWW91I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