emmm...
代码如下
import java.util.ArrayList; import java.util.List; public class Main { private static List<Integer> list = new ArrayList<>(); public static void main(String[] args) { Thread thread1 = new Thread(new TestRunnable(list)); thread1.start(); TestThread thread2 = new TestThread(list); thread2.run(); } static class TestRunnable implements Runnable{ private List<Integer> list; public TestRunnable(List<Integer> list) { this.list = list; } @Override public void run() { Thread.currentThread().setName("Runnable线程"); for(int i=0;i<200;i++){ TestThreadAddList testThreadAddList = new TestThreadAddList(i,list); testThreadAddList.run(); // System.out.println(Thread.currentThread().getName()+"第"+i+"个"); // System.out.println(Thread.currentThread().getName()+"list大小"+list.size()); } } } static class TestThread extends Thread{ private List<Integer> list; public TestThread(List<Integer> list) { this.list = list; } @Override public void run() { Thread.currentThread().setName("Thread线程"); for(int i=0;i<200;i++){ TestThreadAddList testThreadAddList = new TestThreadAddList(i,list); testThreadAddList.run(); // System.out.println(Thread.currentThread().getName()+"list大小"+list.size()); // System.out.println(Thread.currentThread().getName()+"第"+i+"个"); } } } static class TestThreadAddList extends Thread{ private int num; private List<Integer> list; public TestThreadAddList( int num, List<Integer> list) { this.num = num; this.list = list; } @Override public void run() { synchronized (TestThreadAddList.class){ list.add(num); System.out.println(Thread.currentThread().getName()+"list大小"+list.size()); } } } }