首页 > 试题广场 >

多线程打印

[编程题]多线程打印
  • 热度指数:315 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解


创建两个线程,其中一个输出1-52,另外一个输出A-Z。输出格式要求:12A 34B 56C 78D ...


输入描述:
1、线程1打印1-52的数字

2、线程2打印26个字母


输出描述:
每打印两个数字后打印一个字母,直到最终所有数字和字母都打印完成
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    static volatile boolean numberFlag = true;

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Condition number = lock.newCondition();
        Condition word = lock.newCondition();
        Runnable numberTask = () -> {
            try {
                lock.lock();
                for (int i = 1; i <= 52; i++) {
                    while (!numberFlag) {
                       number.await();
                    }
                    System.out.print(i);
                    if(i%2==0){
                        numberFlag=false;
                        word.signalAll();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        };
        Runnable wordTask = () -> {
            try {
                lock.lock();
                for (int i = 0; i < 26; i++) {
                    while (numberFlag){word.await();}
                    char ch = (char) ('a' + i);
                    System.out.print(ch + " ");
                    numberFlag=true;
                    number.signalAll();
                }
                System.exit(0);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        };
        new Thread(numberTask).start();
        new Thread(wordTask).start();
    }

}

发表于 2020-02-15 19:07:02 回复(0)
更多回答
emmm,皮一下
public class Main{
    public static void main(String args[]){
        char c='A';
       for (int i = 1; i <= 52; i++) {
           System.out.print(""+(i++)+i+(c++)+" ");
       }
    }
}


发表于 2020-04-19 21:30:32 回复(1)
import java.util.*;
import java.util.concurrent.*;
public class Main {
  
    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore=new Semaphore(1);
        NumThread numThread = new NumThread(semaphore);
        AlpThread alpThread = new AlpThread(semaphore);
        for(int i=0;i<26;i++){
            new Thread(numThread).start();
            Thread.sleep(1);
            new Thread(alpThread).start();
            Thread.sleep(1);
        }

    }

    static class NumThread implements Runnable{
        private final Semaphore semaphore;
        private int num=1;

        public NumThread(Semaphore semaphore) {
            this.semaphore=semaphore;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.print(num++);
            System.out.print(num++);
            semaphore.release();
        }
    }

    static class AlpThread implements Runnable{
        private final Semaphore semaphore;
        private char alp=65;

        public AlpThread(Semaphore semaphore) {
            this.semaphore=semaphore;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.print(alp++);
            System.out.print(" ");
            semaphore.release();
        }
    }
  
}
编辑于 2020-03-15 20:11:56 回复(3)
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
 
    public static volatile  boolean flag = false;
    public static AtomicInteger time =new AtomicInteger(1);
    public static void main(String[] args) {
 
        new Thread(() -> {
            for (int i = 1; i < 53; i=i+2) {
                if (!flag&&(time.get()==0||time.incrementAndGet()%2==0)) {
 
                        System.out.print(i);
                        System.out.print(i+1);
                        flag=true;
 
 
                }
                else {
                    i=i-2;
                }
 
            }
        }).start();
 
        new Thread(() -> {
            for (int i = 0; i < 26; i++) {
                if (flag&&(time.get()==1||time.incrementAndGet()%2==1)){
              
                        System.out.print((char) (i + 'A'));
                        System.out.print(' ');
                        flag=false;
 
 
                }else {
                    i--;
                }
            }
        }).start();
    }
 
 
}

发表于 2019-12-25 14:10:09 回复(2)

public class Main {

    public static volatile  boolean flag = false;

    public static void main(String[] args) {

        new Thread(() -> {
            for (int i = 1; i < 53; i=i+2) {
                while(flag);
                System.out.print(i);
                System.out.print(i+1);
                flag=true;

            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 26; i++) {
                while(!flag);
                System.out.print((char)(i+'A')+" ");
                flag=false;

            }
        }).start();
    }


}
volatile变量的特性,cpu循环代替wait的效果
发表于 2021-05-12 21:14:15 回复(1)
public class Solution {
    public static void main(String[] args) {
        P p = new P();
        new Thread(() -> {
            for (int i = 0; i < 26; i++) {
                p.printNum();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 26; i++) {
                p.printCH();
            }
        }, "B").start();
    }
}

class P {
    private int flag = 0;
    int a = 0;
    char ch = 'A';

    public synchronized void printNum() {
        if (flag == 1) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {

            }
        }
        System.out.print((++a) + "" + (++a));
        flag = 1;
        this.notifyAll();

    }

    public synchronized void printCH() {
        if (flag == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.print(ch);
        System.out.println();
        ch++;
        flag = 0;
        this.notifyAll();
    }
}
发表于 2021-03-17 00:35:53 回复(0)
public class Test {
    /**
     * 创建两个线程,其中一个输出1-52,另外一个输出A-Z。输出格式要求:12A 34B 56C 78D ...
     */
    public static void main(String[] args) {
        resource resource =new resource();
        new Thread(resource::Num).start();
        new Thread(resource::Letter).start();
    }
}

class resource{
    private ReentrantLock lock =new ReentrantLock();
    private Condition con1 =lock.newCondition();
    private Condition con2 =lock.newCondition();
    public void Num(){
        lock.lock();
        try {
            for (int i=1;i<53;i++) {
                System.out.print(i);
                if(i%2==0) {
                    try {
                        con1.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                con2.signal();
            }
        }finally {
            lock.unlock();
        }
    }
    public void Letter(){
        lock.lock();
        try {
            for (int i = 0;i<26;i++){
                char cha= (char) ('A'+i);
                System.out.print(cha+" ");
                try {
                    con1.signal();
                    con2.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }finally {
            lock.unlock();
        }
    }
}


发表于 2021-03-10 19:32:44 回复(0)
import java.util.Scanner;

public class Solution {
    static final Object object = new Object();
    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {

                for (int i = 1; i <= 52; i += 2) {
                    synchronized (object) {
                        object.notifyAll();
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.printf(String.valueOf(i));
                        System.out.printf(String.valueOf(i + 1));


                        object.notifyAll();
                    }
                }

            }
        });
        t1.start();

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {

                for (int i = 65; i <= 90; i++) {
                    synchronized (object) {
                        object.notifyAll();
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.printf(String.valueOf((char) i) + " ");
                        object.notifyAll();


                    }
                }

            }
        });
        t2.start();

    }
}

发表于 2020-05-10 16:20:35 回复(0)
class MyThread implements Runnable { int count = 0; @Override  public void run() { synchronized (this) { if ("线程一".equals(Thread.currentThread().getName())) { for (int i = 1; i <= 52; i++) { count++; if (count % 3 == 0) { this.notify(); try { this.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print(i); if (i == 52) { this.notify(); try { this.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } if ("线程二".equals(Thread.currentThread().getName())) { for (int i = 65; i <= 90; i++) { char c = (char) i;
                    System.out.print(c + " "); count++; this.notify(); if (i != 90) { try { this.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
} public class Main1 { public static void main(String[] args) {
        MyThread myThread = new MyThread();
        Thread thread = new Thread(myThread, "线程一");
        Thread thread1 = new Thread(myThread, "线程二");
        thread.setPriority(Thread.MAX_PRIORITY);
        thread1.setPriority(Thread.MIN_PRIORITY);
        thread.start();
        thread1.start();
    }
}

发表于 2020-02-27 22:23:48 回复(0)
import threading
lock_1 = threading.Lock()
lock_a = threading.Lock()
def print_1():
    for i in range(1, 53, 2):
        lock_a.acquire()
        print(str(i)+str(i+1), end='')
        lock_1.release()
def print_abc():
    for j in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
        lock_1.acquire()
        print(j, end=' ')
        lock_a.release()
thread_1 = threading.Thread(target=print_1)
thread_a = threading.Thread(target=print_abc)
lock_1.acquire()
thread_1.start()
thread_a.start()

发表于 2019-12-29 18:22:46 回复(0)