让10个线程按顺序打印出0123456789

【让10个线程按顺序打印出0123456789】写代码是一种艺术,不光完成相应的功能,还应该readable 高。关于这个多线程执行,但是顺序打印一串数字,网上有许多例子,我也尝试写了一些:定义了一个IThread线程类,然后又定义了LockObject类,用于保证原子性,测试类为TestThreadOderprint。

package dataalgrithm.link; public class IThread implements Runnable { private LockObject lObject; public void setlObject(LockObject lObject) { this.lObject = lObject; } public int id; public IThread() { } public IThread(int id) { this.id=id; } public void setId(int id) { this.id = id; } public int getId() { return id; } @Override public void run() { synchronized (lObject) { if(lObject.getValue()

package dataalgrithm.link; public class LockObject { int value=https://www.it610.com/article/0; final static int maxvalue=100; public int getValue(){return value; } public void setValue(int value) { this.value = value; }}

package test; import java.util.ArrayList; import java.util.List; import dataalgrithm.link.IThread; import dataalgrithm.link.LockObject; public class TestThreadOderprint { static LockObject lockObject=new LockObject(); public static void main(String[] args) { List list1=new ArrayList(); for (int i = 0; i < 100; i++) { IThread iThread=new IThread(); iThread.setlObject(lockObject); iThread.run(); } }}




    推荐阅读