两个线程交替打印1-10的奇偶数.java

package xiancheng.lunliudayin;
//两个线程交替打印1-10
public class Lunliu1 {
    private int num = 1;
    private Object lock = new Object();
    public void printnum(String name, int target){
        for(int i = 0; i < 5; i++){
            synchronized (lock){
                while(num%2 != target){
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(name+":"+num);
                num++;
                lock.notify();
            }
        }

    }

    public static void main(String[] args) {
        Lunliu1 lunliu1 = new Lunliu1();
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        lunliu1.printnum("even",1);
      

你可能感兴趣的:(【juc多线程】,java,开发语言,后端)