一个线程例子 – 记忆角落

一个线程例子

/ 5评 / 0

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());
            }
        }
    }

}

5条回应:“一个线程例子”

  1. 热福利说道:

    emmm…

    看不懂…

  2. 程志辉说道:

    一起加油吧!【最近在备省赛,看上去简单,但是一个个细节真的头疼死了

  3. xrabbit说道:

    加油

  4. ACG资源说道:

    看来是技术性博客哈!

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注