这篇文章主要介绍了java 多线程有序执行的几种方法总结的相关资料,需要的朋友可以参考下
java 多线程有序执行的几种方法总结
同事无意间提出了这个问题,亲自实践了两种方法。当然肯定还会有更多更好的方法。
方法一
import java.util.concurrent.atomic.atomicinteger;
public class orderedthread1 {
static atomicinteger count = new atomicinteger(0);
public static void main(string[] args) throws interruptedexception {
task task1 = new task(count, 0);
task task2 = new task(count, 1);
task task3 = new task(count, 2);
thread thread1 = new thread(task1);
thread thread2 = new thread(task2);
thread thread3 = new thread(task3);
thread1.setdaemon(true);
thread2.setdaemon(true);
thread3.setdaemon(true);
thread1.start();
thread2.start();
thread3.start();
thread.sleep(1 * 1000);
}
}
class task implements runnable {
private atomicinteger count;
private int order;
public task(atomicinteger count, int order) {
this.count = count;
this.order = order;
}
@override
public void run() {
while (true) {
if (count.get() % 3 == order) {
system.out.println(thread.currentthread().getname() + " ===== "+ order);
count.incrementandget();
}
}
}
}
这种方法应该是比较常见的解决方案。利用原子递增控制线程准入顺序。
方法二
public class orderedthread2 {
static holder holder = new holder();
public static void main(string[] args) throws interruptedexception {
task1 task1 = new task1(holder, 0);
task1 task2 = new task1(holder, 1);
task1 task3 = new task1(holder, 2);
thread thread1 = new thread(task1);
thread thread2 = new thread(task2);
thread thread3 = new thread(task3);
thread1.setdaemon(true);
thread2.setdaemon(true);
thread3.setdaemon(true);
thread1.start();
thread2.start();
thread3.start();
thread.sleep(1 * 1000);
}
}
class task1 implements runnable {
holder holder;
int order;
public task1(holder holder, int order) {
this.holder = holder;
this.order = order;
}
@override
public void run() {
while (true) {
if (holder.count % 3 == order) {
system.out.println(thread.currentthread().getname() + " ===== "+ order);
holder.count ++;
}
}
// int i = 0;
// while(i ++ < 10000){
// holder.count ++;
// }
}
}
class holder {
volatile int count = 0;
}
方法二使用了volatile关键字。让每个线程都能拿到最新的count的值,当其中一个线程执行++操作后,其他两个线程就会拿到最新的值,并检查是否符合准入条件。
ps:volatile不是线程安全的。而且两者没有任何关系。volatile变量不在用户线程保存副本,因此对所有线程都能提供最新的值。但试想,如果多个线程同时并发更新这个变量,其结果也是显而易见的,最后一次的更新会覆盖前面所有更新,导致线程不安全。在方法二中,一次只有一个线程满足准入条件,因此不存在对变量的并发更新。volatile的值是最新的与线程安全完全是不相干的,所以不要误用volatile实现并发控制。
以上就是java多线程有序执行的几种方法的示例代码的详细内容。
