多线程顺序打印0-100等问题

问题描述:

  • 3个线程,顺序打印1-100,线程1打印123,线程2打印456,线程3打印789。。。以此类推
package com.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by yanwen.ayw on 2016/10/9.
 * desc:
 */
public class ThreadAdd implements Runnable{
    private static final String TAG = "ThreadAdd";

    private static int si = 0;

    private int id;

    ThreadAdd(int id) {
        this.id = id;
    }

    @Override
    public void run() {
            synchronized (ThreadAdd.class) {
                while (si < 100) {
                if(si / 3 % 3 == id) {
                    System.out.print("Thread-"+ id + "--->");
                    for(int i = 0; i < 3; i++) {
                        System.out.print("   " + si++);
                    }
                    System.out.println();
                    ThreadAdd.class.notifyAll();
                } else {
                    try {
                        ThreadAdd.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        ThreadAdd t1 = new ThreadAdd(0);
        ThreadAdd t2 = new ThreadAdd(1);
        ThreadAdd t3 = new ThreadAdd(2);
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(t1);
        executorService.execute(t2);
        executorService.execute(t3);
    }
}
  • 一个数,一个线程+1 一个线程-1 交替
public class Print {
    private int i;

    public static void main(String[] args) {
        new Print().print();
    }

    private void print() {
        new Thread(new Add()).start();
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(new Sub()).start();
    }

    public int getInt() {
        return i;
    }

    public void setInt(int i) {
        this.i = i;
    }

    private class Add implements Runnable {
        @Override
        public void run() {
            while (true) {
                synchronized (Print.class) {
                    setInt(getInt() + 1);
                    System.out.println("thread-1 : " + getInt());
                    Print.class.notifyAll();
                    try {
                        Print.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private class Sub implements Runnable {
        @Override
        public void run() {
            while (true) {
                synchronized (Print.class) {
                    setInt(getInt() - 1);
                    System.out.println("thread-2 : " + getInt());
                    Print.class.notifyAll();
                    try {
                        Print.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
  • 多线程数组求和(此处要注意,如果数组或者数字过大,需要考虑越界问题,用long或者BigInteger来存储结果)
public class ArraySum {
    private static final int SIZE = 16;
    private int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 11, 12, 23, 23, 33, 22, 123, 43, 54, 65, 78, 32, 43, 123, 2, 3, 55, 32, 323, 54, 3, 231, 32,
            123, 32, 54, 78, 5, 4, 43, 23, 43, 67, 43, 32, 43, 21, 32, 12, 32, 54, 65, 87, 23, 1, 23, 43, 132, 34, 31, 23, 12, 32, 243, 32};

    public static void main(String[] args) {
        new ArraySum().sumArray();
    }

    private void sumArray() {
        int sum = 0;
        int num = array.length / SIZE;
        if (array.length % SIZE != 0) {
            num++;
        }
        List res = new ArrayList<>(num);
        CountDownLatch startLatch = new CountDownLatch(1);
        CountDownLatch doneLatch = new CountDownLatch(num);
        for (int i = 0; i < num; i++) {
            Thread t = new Thread(new addThread(i * SIZE,
                    (i + 1) * SIZE < array.length ? (i + 1) * SIZE : array.length,
                    startLatch, doneLatch, res));
            t.start();
        }
        startLatch.countDown();
        System.out.println("begin calc...");
        try {
            doneLatch.await();
            for (int i : res) {
                sum += i;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("calc end, result : " + sum);
    }

    public int[] getArray() {
        return array;
    }

    private class addThread implements Runnable {
        private int start, end;
        private CountDownLatch doneLatch;
        private CountDownLatch startLatch;
        private List list;

        addThread(int start, int end, CountDownLatch startLatch, CountDownLatch doneLatch, List res) {
            this.start = start;
            this.end = end;
            this.doneLatch = doneLatch;
            this.startLatch = startLatch;
            this.list = res;
        }

        @Override
        public void run() {
            try {
                startLatch.await();
                int sum = 0;
                int[] array = getArray();
                for (int i = start; i < end; i++) {
                    sum += array[i];
                }
                synchronized (ArraySum.class) {
                    list.add(sum);
                    System.out.println("thread" + start + "-" + end + " calc :" + sum);
                }
                doneLatch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

你可能感兴趣的:(Java)