简体   繁体   English

Java多线程在main中的两个类

[英]Java Multithreading two classes in main

I am very new to programming, and I am trying to write a Java program with the Timer and ChecksUserInput classes shown below.我对编程很ChecksUserInput ,我正在尝试使用下面显示的TimerChecksUserInput类编写 Java 程序。 How do I get them to run at the same time in the main class?如何让它们在主类中同时运行?

I am also having issues with printing out the word length in ChecksUserInput .我在打印ChecksUserInput的字长时也遇到问题。

main.java : main.java

package application;

public class Main {
    public static void main(String[] args) {
        CreateBoard board = new CreateBoard();
        board.run();

        Timer timer = new Timer();
        timer.run();

        ChecksUserInput input = new ChecksUserInput();
        input.run();
    }
}

timer.java : timer.java :

package application;

public class Timer {
    private static void time() {
        final int mili = 1000;
        final int sec = 60;
        final int oneMinute = (mili * sec);

        System.out.println("Start 3 minute timer");
        sleep(oneMinute * 2);

        System.out.println("One minute remaining...");
        sleep(oneMinute);

        System.out.println("Time's up!");
    }

    private static void sleep(int sleepTime) {
        try {
            Thread.sleep(sleepTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        time();
    }
}

checksuserinput.java : checksuserinput.java

package application;

import java.util.*;

public class ChecksUserInput {
    private static String UserInput() {
        Scanner sc = new Scanner(System.in);
        System.out.println("Begin entering words!");

        String word = null;
        for (int i = 0; i < 10000; i++) {
            word = sc.nextLine();
        }

        return word;
    }

    private static int length(String word) {
        int wordLength = word.length();
        return wordLength;
    }

    public void run() {
        String userWord = UserInput();
        int wordLength = length(userWord);
        System.out.println(wordLength);
    }
}

You should search "java multithreading" on your favourite search engine and compare your code with those examples您应该在您最喜欢的搜索引擎上搜索“java multithreading”并将您的代码与这些示例进行比较

You will find that these people have (mostly) implemented the Runnable interface on their classes.你会发现这些人(大部分)已经在他们的类上实现了 Runnable 接口。 So所以

-- public class ChecksUserInput { -- 公共类 ChecksUserInput {

++ public class ChecksUserInput implements Runnable{ ++ 公共类 ChecksUserInput 实现 Runnable{

And run() was a method of that interface, that they had to implement.而 run() 是该接口的一个方法,他们必须实现。

Your version first runs the run method of the first class, then the other.您的版本首先运行第一个类的 run 方法,然后是另一个。 But when you implement the runnable interface, the both run methods will be called right after one another, without waiting for the first one to finish但是当你实现了 runnable 接口时,两个 run 方法会一个接一个地被调用,而不用等待第一个调用完成

You should search on your own and find more examples, or check the documentations for multithreading if you face any other issues您应该自己搜索并找到更多示例,或者如果您遇到任何其他问题,请查看多线程文档

So after the wonderful help @BATIKAN BORA ORMANCI and @mike1234569 gave me along with this link https://www.geeksforgeeks.org/multithreading-in-java/ I was able to actually figure it out所以在@BATIKAN BORA ORMANCI 和@mike1234569 给了我这个链接https://www.geeksforgeeks.org/multithreading-in-java/的精彩帮助之后,我真的弄清楚了

package application;打包申请;

public class Main {公共课主要{

public static void main(String[] args) {

    CreateBoard board = new CreateBoard();
    board.run();

    Thread timer = new Thread(new Timer());
    Thread input = new Thread(new ChecksUserInput());

    timer.start();
    input.start();

    try {
        timer.join();
        input.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

} }

and I set my classes to implement Runnable as Batikan suggested我按照 Batikan 的建议将我的课程设置为实现 Runnable

The foundation of multi-threading in Java is the Thread class. Java 中多线程的基础是 Thread 类。 The general structure for usage is:使用的一般结构是:

Thread newProcess = new Thread(processToRun); //Create a thread which will execute the process
newProcess.setDaemon(true/false); //when false, the thread will keep the JVM alive beyond completion of 'main'
newProcess.start(); //Start processToRun in a new thread

To start several independent processes, this should be sufficient.要启动几个独立的进程,这应该就足够了。 For example, the following starts 10 threads each of which will print the index in the loop.例如,以下启动 10 个线程,每个线程将在循环中打印索引。 At the end, the process sleeps for 5 milliseconds because the spawned threads are daemon.最后,进程休眠 5 毫秒,因为产生的线程是守护进程。 Removing this may cause the process to terminate before any messages are printed.删除它可能会导致进程在打印任何消息之前终止。

    public static void main(String args[]) throws Exception
    {
        for(int i = 0; i < 10; i++) { int index = i; start(() -> System.out.println(index)); }
        Thread.sleep(5);
    }

    public static void start(Runnable processToRun)
    {
        Thread newProcess = new Thread(processToRun);
        newProcess.setDaemon(true);
        newProcess.start();
    }

Beyond this point questions start to get more complicated/contextual.超出这一点的问题开始变得更加复杂/上下文。 Ex:前任:

  1. How can processes running in 2 threads communicate with each other?在 2 个线程中运行的进程如何相互通信?
  2. How can processes running in 2 threads access/modify common state between them?在 2 个线程中运行的进程如何访问/修改它们之间的公共状态?

In the context of creating a simple game, one option is to use Queues to feed user inputs to the game and have the game process updates in a single thread.在创建简单游戏的上下文中,一种选择是使用队列将用户输入提供给游戏,并在单个线程中更新游戏进程。 The following sample listens for the user inputting commands (Up, Down, Left, Right) on the main thread and adds valid commands to a queue.以下示例在主线程上侦听用户输入命令(上、下、左、右)并将有效命令添加到队列中。 Valid commands are polled and processed in a different thread to update the location on the board.在不同的线程中轮询和处理有效命令以更新板上的位置。

Sample:样本:

    public static void main(String args[])
    {
        Board board = new Board();
        BlockingQueue<Move> movesQueue = new ArrayBlockingQueue<>(100);
        Scanner systemListener = new Scanner(System.in);
        start(() -> routeBoardMovesToQueue(board, movesQueue)); /*route moves from the queue to the board in a new thread*/
        while(true)
        {
            Optional<Move> nextMove = Move.resolve(systemListener.nextLine());
            if(nextMove.isPresent())
                movesQueue.offer(nextMove.get()); /*Write moves from System.in to the queue*/
            else
                System.out.println("Invalid Move Provided");
        }
    }
    
    public static void routeBoardMovesToQueue(Board board, BlockingQueue<Move> movesQueue)
    {
        try
        {
            while(true)
            {
                Move next = movesQueue.poll(100_000, TimeUnit.DAYS);
                if(next != null) board.performMove(next);
            }
        }
        catch(InterruptedException ignored){ System.out.println("Stopping"); }
    }

    public static void start(Runnable processToRun)
    {
        Thread newProcess = new Thread(processToRun);
        newProcess.setDaemon(true);
        newProcess.start();
    }

    public static final class Board
    {
        private final Location location;
        public Board(){ this.location = new Location(); }
        public void performMove(Move move)
        {
            switch(move)
            {
                case Up:    location.y += 1; break;
                case Down:  location.y -= 1; break;
                case Right: location.x += 1; break;
                case Left:  location.x -= 1; break;
            }
            System.out.println("New Position: (" + location.x + ", " + location.y + ")");
        }

        public static class Location{ int x = 0; int y = 0; }
    }

    public enum Move
    {
        Up, Down, Left, Right;
        public static Optional<Move> resolve(String move){ return Stream.of(Move.values()).filter(mv -> Objects.equals(move, mv.name())).findAny(); }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM