Java多线程

题目描述:

有三个线程,要求分别在控制台输入后进行字符串的拼接"_A","_B","_C"。

条件是:

  1.线程能顺序执行,线程1执行出“_A”,线程2执行“_B”,线程3执行“_C”;

  2.三个线程同时启动。

代码如下:

import java.util.Scanner;
import java.util.concurrent.CountDownLatch;

public class Main {

	private int i = 0;
	private static StringBuffer sb = new StringBuffer();
	private static CountDownLatch cd = new CountDownLatch(3);
	
	public static void main(String[] args) throws InterruptedException {
		Scanner in = new Scanner(System.in);
		String str = in.nextLine();
		sb.append(str);
		
		Thread pre = new Thread(new Runnable() {
			
			@Override
			public void run() {
				sb.append(Thread.currentThread().getName());
				cd.countDown();
			}
		},"_A");
		pre.start();
		for(int i = 1;i < 3;i++) {
			Thread thread;
			if(i == 1) {
				thread = new Thread(new Thr(pre),"_B");
			}else {
				thread = new Thread(new Thr(pre),"_C");
			}
			thread.start();
			pre = thread;
		}
		cd.await();
		System.out.println(sb.toString());
	}
	static class Thr implements Runnable{

		private Thread thread;
		public Thr(Thread thread) {
			this.thread = thread;
		}
		@Override
		public void run() {

			try {
				thread.join();
			}catch(InterruptedException e) {
				
			}
			sb.append(Thread.currentThread().getName());
			cd.countDown();
		}
		
	}

}

 若是只是顺序打印ABC的话:

package com.ymm.thread;

public class JionMain {

    public static void main(String[] args){

        ThreadA threadA  = new ThreadA();
        ThreadB threadB = new ThreadB(threadA);
        ThreadC  threadC = new ThreadC(threadB);
        threadA.start();
        threadB.start();
        threadC.start();

    }
}

class ThreadA extends  Thread{

    @Override
    public void run(){
        System.out.println("A");
    }
}
class ThreadB extends  Thread {
    private ThreadA threadA;

    public ThreadB(ThreadA threadA) {
        this.threadA = threadA;

    }

    @Override
    public void run() {
        try {
            threadA.join();
        } catch (InterruptedException e) {

        }
        System.out.println("B");
    }
}
    class ThreadC extends Thread {
        private ThreadB threadB;

        public ThreadC(ThreadB threadB) {
            this.threadB = threadB;

        }

        @Override
        public void run() {
            try {
                threadB.join();
            } catch (InterruptedException e) {

            }
            System.out.println("C");
        }
    }

 

posted @ 2019-08-30 17:27  离愁i  阅读(169)  评论(0编辑  收藏  举报