多线程---有四个线程1、2、3、4。线程1的功能就是输出1,线程2的功能就是输出2,以此类推.........现在有四个文件ABCD

有四个线程1、2、3、4。

线程1的功能就是输出1,

线程2的功能就是输出2,以此类推………现在有四个文件ABCD。

初始都为空。

现要让四个文件呈如下格式:

A:1 2 3 4 1 2….

B:2 3 4 1 2 3….

C:3 4 1 2 3 4….

D:4 1 2 3 4 1….

请设计程序。

先试着写出四个线程交替写入A文件

public class FourThreadOneFile
{
    public static FILE file = new FILE();

    public static void main(String[] args)
    {
        System.out.println("Hello World!");
        ExecutorService executors = Executors.newFixedThreadPool(5);
        executors.execute(new PrintTask(1));
        executors.execute(new PrintTask(2));
        executors.execute(new PrintTask(3));
        executors.execute(new PrintTask(4));
        executors.shutdown();
    }
    static class PrintTask implements Runnable
    {
        private int id = 0;
        public PrintTask(int id){
            this.id = id;
        }
        public void run(){
            while(true){
                file.print(id);
            }
        }
    }
}

class FILE
{
    //private static Lock = new ReentrantLock();
    private static int state = 0;
    private static PrintWriter out;

    public FILE(){
        try{
            out = new PrintWriter("A.txt");
        }catch(Exception fileNotFound){

        }
    }

    public static synchronized void  print(int id) {
        if(state == (id - 1)){
            try{
                out.print(id);
                System.out.println(id);
                Thread.sleep(1000);
            }catch(InterruptedException ex1){

            }finally{
                //刷新缓冲区
                out.flush();
            }
            state++;
            if(state == 4){
                out.println();
                state = 0;
            }
        }
    }
}

扩展到四个文件

为任务类指定id和name

id表示打印的顺序

name表示打印时打印的字符

id需要根据情况在文件类里时刻调整顺序

public class FourThreadFourFile
{
    public static FILE file = new FILE();

    public static void main(String[] args) throws Exception
    {
        System.out.println("Hello World!");
        PrintWriter o = new PrintWriter("B");
        o.println("hello");
        o.close();
        ExecutorService executors = Executors.newFixedThreadPool(5);
        executors.execute(new PrintTask(1,"1"));
        executors.execute(new PrintTask(2,"2"));
        executors.execute(new PrintTask(3,"3"));
        executors.execute(new PrintTask(4,"4"));
        executors.shutdown();
    }
    public static class PrintTask implements Runnable
    {
        private int id = 0;
        public String name;
        public PrintTask(int id,String name){
            this.id = id;
            this.name = name;
        }
        public void run(){
            while(true){
                file.printFile(id,this);
            }
        }
    }
}

class FILE
{
    //private static Lock = new ReentrantLock();
    //代表需要打印的数
    private static int state = 0;
    //选择操作文件
    //0---A
    //1---B
    //2---C
    //3---D
    private static int select = 0;
    private static PrintWriter outA;
    private static PrintWriter outB;
    private static PrintWriter outC;
    private static PrintWriter outD;

    private static PrintWriter out;
    public FILE(){
        try{
            outA = new PrintWriter("A.txt");
            outB = new PrintWriter("B.txt");
            outC = new PrintWriter("C.txt");
            outD = new PrintWriter("D.txt");

        }catch(Exception fileNotFound){

        }
    }
    public static synchronized void printFile(int id,FourThreadFourFile.PrintTask pt){
        switch(select){
            case 0:
                out = outA;
                print(id,pt);
                break;
            case 1:
                out = outB;
                //调整id
                id = id - 1;
                if(id <= 0){
                    id += 4;
                }
                print(id,pt);
                break;
            case 2:
                out = outC;
                //调整id
                id = id - 2;
                if(id <= 0){
                    id += 4;
                }
                print(id,pt);
                break;
            case 3:
                out = outD;
                id = id - 3;
                //调整id
                if(id <= 0){
                    id += 4;
                }
                print(id,pt);
                break;
        }

    }

    public static synchronized void  print(int id,FourThreadFourFile.PrintTask pt) {
        if(state == (id - 1)){
            try{
                out.print(pt.name);
                System.out.println((char)(‘A‘+select)+"-----" + pt.name);
                Thread.sleep(1000);
            }catch(InterruptedException ex1){

            }finally{
                //刷新缓冲区
                out.flush();
            }
            state++;
            if(state == 4){
                out.println();
                state = 0;
                select++;
                if(select == 4){
                    select = 0;
                }
            }
        }
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-08-06 11:39:32

多线程---有四个线程1、2、3、4。线程1的功能就是输出1,线程2的功能就是输出2,以此类推.........现在有四个文件ABCD的相关文章

Google面试题—有四个线程1、2、3、4。线程1的功能就是输出1,线程2的功能就是输出2,以此类推.........现在有四个文件ABCD

分类: windows编程 C++ 2012-10-27 19:56 3410人阅读 评论(1) 收藏 举报 有四个线程1.2.3.4.线程1的功能就是输出1,线程2的功能就是输出2,以此类推.........现在有四个文件ABCD.初始都为空.现要让四 个文件呈如下格式:A:1 2 3 4 1 2....B:2 3 4 1 2 3....C:3 4 1 2 3 4....D:4 1 2 3 4 1....请设计程序. [cpp] view plaincopy #include <stdio.h

Linux下多线程查看工具(pstree、ps、pstack),linux命令之-pstree使用说明, linux 查看线程状态。 不指定

0.最常用 pstree:[[email protected] temp]# pstree -a|grep multe  |       |   `-multepoolser  |       |       `-multepoolser  |       |           `-2*[{multepoolser}] 1. > top 可以显示所有系统进程 按u, 再输入相应的执行用户名称,比如Tom 可以看到Tom用户启动的所有进程和对应的pid 2. > pstack pid 可以看到

开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上,要求输出结果必须按ABC的顺序显示:ABCABC

分类: windows编程 C++ 2012-10-27 15:38 3270人阅读 评论(6) 收藏 举报 第四题(迅雷笔试题):编写一个程序,开启3个线程,这3个线程的ID分别为A.B.C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示:如:ABCABC….依次递推. [cpp] view plaincopy #include <stdio.h> #include <process.h> #include <windows.h> #def

python-多线程:调用thread模块中的start_new_thread()函数来产生新线程

Python 多线程 多线程类似于同时执行多个不同程序,多线程运行有如下优点: 使用线程可以把占据长时间的程序中的任务放到后台去处理. 用户界面可以更加吸引人,这样比如用户点击了一个按钮去触发某些事件的处理,可以弹出一个进度条来显示处理的进度 程序的运行速度可能加快 在一些等待的任务实现上如用户输入.文件读写和网络收发数据等,线程就比较有用了.在这种情况下我们可以释放一些珍贵的资源如内存占用等等. 线程在执行过程中与进程还是有区别的.每个独立的线程有一个程序运行的入口.顺序执行序列和程序的出口.

WebApi 数据保护操作未成功。这可能是由于未为当前线程的用户上下文加载用户配置文件导致的。当线程执行模拟时,可能会出现此情况。&quot;,&quot;ExceptionType&quot;:&quot;System.Security.Cryptography.CryptographicException&quot;,&quot;StackTrace

在调用System.Security.Cryptography.ProtectedData.Protect方法来保护私密信息时,IIS可能会报以下错误:CryptographicException: 数据保护操作未成功.这可能是由于未为当前线程的用户上下文加载用户配置文件导致的.当线程执行模拟时,可能会出现此情况. 解决方法:1.打开应用程序池2.在应用程序上右键选择高级设置3.进程模型下设置“加载用户配置文件”为True

Qt 多线程与数据库操作需要注意的几点问题(QSqlDatabase对象只能在当前线程里使用)

彻底抛弃MFC, 全面应用Qt 已经不少时间了.除了自己看书按步就班做了十几个验证性的应用,还正式做了3个比较大的行业应用,总体感觉很好.Native C++ 下, Qt 基本是我用过的最简便的界面库了.遇到了一些问题,大都解决的很顺利,回头想想,还是有几个问题很有意思,尤其是数据库应用.这里把我的经历分享一下. 1.线程内注册与连接数据库的竞争问题 文档上对多线程下数据库应用的注意事项写的很简明,一个线程创建的 QSqlDatabase 对象和 查出来的 QSqlQuery 对象只能给本线程用

可重入与线程安全(大多数Qt类是可重入,非线程安全的)

可重入与线程安全 在Qt文档中,术语“可重入”与“线程安全”被用来说明一个函数如何用于多线程程序.假如一个类的任何函数在此类的多个不同的实例上,可以被多个线程同时调用,那么这个类被称为是“可重入”的.假如不同的线程作用在同一个实例上仍可以正常工作,那么称之为“线程安全”的. 大多数c++类天生就是可重入的,因为它们典型地仅仅引用成员数据.任何线程可以在类的一个实例上调用这样的成员函数,只要没有别的线程在同一个实例上调用这个成员函数.举例来讲,下面的Counter 类是可重入的: class Co

记录一次线程池的在项目中的实际应用,讲解一下线程池的配置和参数理解。

前言:最近项目中与融360项目中接口对接,有反馈接口(也就是我们接收到请求,需要立即响应,并且还要有一个接口推送给他们其他计算结果),推送过程耗时.或者说两个接口不能是同时返回,有先后顺序. 这时我想到了把自己Controller立即返回接受成功,中间添加一个新的线程去做其他耗时的操作(线程池配置和参数测试讲解请阅读第5步). 1.Controller代码如下: @Autowiredprivate CallThreadDemo worker; @RequestMapping("/bandBank

一个主线程下有多个子线程任务,主线程必须在100秒内将子线程执行的集合结果进行处理返回

实现代码: package cmd.chengxuyuanzhilu.async; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future;