我不知道他们在这个实验中试图告诉我做什么

问题描述 投票:0回答:1

我最近已经开始研究操作系统,并且我们的讲座不足以了解家庭作业。

问题是:执行TwoThreads示例。然后修改程序,使其仅使用一个线程类ThreadAB。在类的构造函数中,您应该传递两个字符串,这些字符串应由相应的实例打印出来。该线程不应继承Thread类。新程序的行为应与原始程序相同,即,您必须再次有两个线程将分别执行run()方法:一个线程将打印A和B,而另一个线程将打印1和2。

如果一个线程需要打印出从A到F的字符,而另一个线程需要打印从1到15的数字,将会发生什么?您可以正确预测程序输出吗?

为什么我需要为每个实例传递两个字符串?如何使程序知道要运行哪个线程?

这是他们告诉我们更改的程序(我完全理解):

public class TwoThreads {
    public static class Thread1 extends Thread {
        public void run() {
            System.out.println("A");
            System.out.println("B");
        }
    }

    public static class Thread2 extends Thread {
        public void run() {
            System.out.println("1");
            System.out.println("2");
        }
    }

    public static void main(String[] args) {
        new Thread1().start();
        new Thread2().start();
    }

这是我的“至少您尝试过”的程序:

public class TwoThreads {

    public static class ThreadAB implements Runnable {
        private String name;

        public ThreadAB (String name) {
            this.name = name;
        }

        @Override
        public void run() {
            System.out.println("A");
            System.out.println("B");
        }

    }

    public static void main(String[] args) {
        Runnable t1 = new ThreadAB("Thread1");
        Runnable t2 = new ThreadAB("Thread2");

        ((Thread) t1).start();
        ((Thread) t2).start();
    }
}

我得到的错误是:

Exception in thread "main" java.lang.ClassCastException: prvaZad.TwoThreads$ThreadAB cannot be cast to java.lang.Thread
    at prvaZad.TwoThreads.main(TwoThreads.java:24)

先谢谢您。

编辑(该错误的注释解决方案::]

public static void main(String[] args) {
        Runnable t1 = new ThreadAB("Thread1");
        Runnable t2 = new ThreadAB("Thread2");

        Thread th1 = new Thread(t1);
        Thread th2 = new Thread(t2);

        th1.start();
        th2.start();
    }

我最近开始研究操作系统,我们的讲座内容不足以理解家庭作业。问题是:执行TwoThreads示例。然后修改...

java multithreading runnable
1个回答
0
投票

我相信他们正在寻找类似的东西:

© www.soinside.com 2019 - 2024. All rights reserved.