如下例子所示:
package xiaoye.java; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicLong; public class Test { public static void main(String[] args) { ExecutorService pool = Executors.newFixedThreadPool(2); Runnable t1 = new MyRunnable("张三", 2000); Runnable t2 = new MyRunnable("李四", 3600); Runnable t3 = new MyRunnable("王五", 2700); Runnable t4 = new MyRunnable("老张", 600); Runnable t5 = new MyRunnable("老牛", 1300); Runnable t6 = new MyRunnable("老朱", 800); //执行各个线程 pool.execute(t1); pool.execute(t2); pool.execute(t3); pool.execute(t4); pool.execute(t5); pool.execute(t6); //关闭线程池 pool.shutdown(); } } class MyRunnable implements Runnable { private static AtomicLong aLong = new AtomicLong(10000); //原子量,每个线程都可以自由操作 private String name; //操作人 private int data; //操作数 MyRunnable(String name, int data) { this.name = name; this.data = data; } public void run() { Thread.yield(); System.out.println(name + "执行了" + data + ",当前余额:" + aLong.addAndGet(data)); } }
对于
System.out.println(name + "执行了" + data + ",当前余额:" + aLong.addAndGet(data));
System.out.println((new StringBuilder(String.valueOf(name))).append("执行了").append(data).append(",当前余额:").append(aLong.addAndGet(data)).toString());
public void println(String x) { synchronized (this) { print(x); newLine(); } }
实际上的执行过程是: 张三——李四——王五——老张——老牛——老朱,而实际上输出 张三 却是称为最后一个输出的。这是因为 张三 在或的锁之前被打断了。
如果我们想要输出正确的执行顺序,可以加一个显示锁:
package xiaoye.java; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Test { public static void main(String[] args) { ExecutorService pool = Executors.newFixedThreadPool(2); Lock lock = new ReentrantLock(false); Runnable t1 = new MyRunnable("张三", 2000, lock); Runnable t2 = new MyRunnable("李四", 3600, lock); Runnable t3 = new MyRunnable("王五", 2700, lock); Runnable t4 = new MyRunnable("老张", 600, lock); Runnable t5 = new MyRunnable("老牛", 1300, lock); Runnable t6 = new MyRunnable("老朱", 800, lock); // 执行各个线程 pool.execute(t1); pool.execute(t2); pool.execute(t3); pool.execute(t4); pool.execute(t5); pool.execute(t6); // 关闭线程池 pool.shutdown(); } } class MyRunnable implements Runnable { private static AtomicLong aLong = new AtomicLong(10000); // 原子量,每个线程都可以自由操作 private Lock lock; private String name; // 操作人 private int data; // 操作数 MyRunnable(String name, int data, Lock lock) { this.name = name; this.data = data; this.lock = lock; } public void run() { lock.lock(); System.out.println(name + "执行了" + data + ",当前余额:" + aLong.addAndGet(data)); lock.unlock(); } }
原文地址:http://blog.csdn.net/zq602316498/article/details/40398247