两个线程顺序有序执行

两个线程顺序有序执行,两个方法:1 用interrupt 和 sleep 2 用注释中的synchronized,signalAll ,sleep

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Test91 {
 
    private static Thread t1;
    private static Thread t2;
    private static Thread t3;
    private static List integers;
    private static int i = 0;
    static final int MAX = 1000;
    private static final int ThreadCount = 2;
 
    public static void main(String... args) throws InterruptedException {
        integers = Collections.synchronizedList(new ArrayList(ThreadCount * MAX));
        t1 = new MyThread1();
        t1.start();
        t2 = new MyThread2();
        t2.start();
    }
 
    private static void check() {
        System.out.println();
        System.out.println("---------------------");
        for (int i = 0; i < integers.size() - ThreadCount; i++) {
            if (i % 2 == 0) {
                if (!integers.get(i).equals(integers.get(i + ThreadCount - 1))) {
                    System.out.println(integers.get(i) + "和" + integers.get(i + 1) + "不相等");
                    break;
                }
            }
        }
    }
 
    static class MyThread1 extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < MAX; i++) {
                System.out.print(i + "\t");
                integers.add(i);
                runThread(t2, t1);
            }
        }
    }
 
    static class MyThread2 extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < MAX; i++) {
                System.out.print(i + "\t");
                integers.add(i);
                runThread(t1, t2);
            }
        }
    }
 
    private static Lock lock = new ReentrantLock();
    private static final Object object = new Object();
 
    static void runThread(Thread t1, Thread t2) {
//        synchronized (object) {
//            object.notifyAll();
//            try {
//                if (++i >= ThreadCount * MAX) {
//                    check();
//                } else {
//                    object.wait();
//                }
//
//            } catch (Exception e) {
//            }
//        }
        try {
            t1.interrupt();//让另一个线程终端睡眠
            if (++i >= ThreadCount * MAX) {
                check();
            } else {
                //System.out.print(t1.getName());
                Thread.sleep(1000);//让当前线程睡眠
            }
 
        } catch (Exception e) {
        }
    }
}

你可能感兴趣的:(两个线程顺序有序执行)