使用Runnable接口
public class ThreadTest {
int count = 0;
public static void main(String[] args) {
ThreadTest threadTest = new ThreadTest();
MyRunnable myRunnable = threadTest.new MyRunnable();
MyRunnable myRunnable1 = threadTest.new MyRunnable();
MyRunnable myRunnable2 = threadTest.new MyRunnable();
MyRunnable myRunnable3 = threadTest.new MyRunnable();
MyRunnable myRunnable4 = threadTest.new MyRunnable();
new Thread(myRunnable).start();
new Thread(myRunnable1).start();
new Thread(myRunnable2).start();
new Thread(myRunnable3).start();
new Thread(myRunnable4).start();
}
class MyRunnable implements Runnable{
@Override
public void run() {
while (true){
synchronized (MyRunnable.class){
if(count > 100){
break;
}
System.out.println(Thread.currentThread().getName() + ":count" + (++ count));
Thread.yield();
}
}
}
}
}
使用AtomicInteger加线程池
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadTest1 {
static CountDownLatch cdl = new CountDownLatch(100);
static AtomicInteger ai = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
ExecutorService exec = Executors.newFixedThreadPool(10);
for (int i = 0; i < 100; i++) {
exec.execute(() -> {
System.out.println(Thread.currentThread().getName() + ":" + ai.getAndIncrement());
cdl.countDown();
});
}
cdl.await();
System.out.println(ai.get());
exec.shutdown();
}
}