多线程

题目描述:

问题描述:有4个线程和1个公共的字符数组。线程1的功能就是向数组输出A,线程2的功能就是向字符输出B,线程3的功能就是向数组输出C,线程4的功能就是向数组输出D。要求按顺序向数组赋值ABCDABCDABCD,ABCD的个数由线程函数1的参数指定。[注:C语言选手可使用WINDOWS SDK库函数]

输入描述:

输入一个int整数

输出描述:

输出多个ABCD

import java.util.Scanner;

public class Main
{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext())
        {
            int x = scanner.nextInt();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < x; i++)
                sb.append("ABCD");
            System.out.println(sb.toString());
        }
    }
}
以下方法:运行超时
/*import java.io.BufferedReader;
import java.io.InputStreamReader;*/
import java.util.Scanner;

public class Main
{
    public static void main(String[] args) throws Exception{
        Object a = new Object();
        Object b = new Object();
        Object c = new Object();
        Object d = new Object();

        /*InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        int count = Integer.valueOf(br.readLine());*/
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext())
        {
            int count = scanner.nextInt();
            MyThreadPrinter2 pa = new MyThreadPrinter2("A", d, a, count);
            MyThreadPrinter2 pb = new MyThreadPrinter2("B", a, b, count);
            MyThreadPrinter2 pc = new MyThreadPrinter2("C", b, c, count);
            MyThreadPrinter2 pd = new MyThreadPrinter2("D", c, d, count);

            new Thread(pa).start();
            Thread.sleep(100);
            new Thread(pb).start();
            Thread.sleep(100);
            new Thread(pc).start();
            Thread.sleep(100);
            new Thread(pd).start();
        }


    }
}

class MyThreadPrinter2 implements Runnable
{
    public String name;
    public Object prev;
    public Object self;
    public int count;
    public MyThreadPrinter2(String name, Object prev, Object self, int count)
    {
        this.name = name;
        this.prev = prev;
        this.self = self;
        this.count = count;
    }

    public void run()
    {
        while (count > 0)
        {
            synchronized (prev)
            {
                synchronized (self)
                {
                    System.out.print(name);
                    count--;
                    self.notify();
                }
                if (count == 0)
                    break;
                try
                {
                    prev.wait();
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
}

你可能感兴趣的:(华为机试)