下面是一个示例代码,用于创建一个线程来打印字符:

public class CharPrinter implements Runnable {
    private char ch;

    public CharPrinter(char ch) {
        this.ch = ch;
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.print(ch);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new CharPrinter('A'));
        Thread t2 = new Thread(new CharPrinter('B'));

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

这里我们定义了一个 CharPrinter 类实现了 Runnable 接口,并在其构造函数中传入一个字符参数 ch。在 run() 方法中,我们使用 for 循环打印该字符 10 次,并在每次打印后休眠 100 毫秒。

在 main() 方法中,我们分别创建了两个线程 t1 和 t2,并将 CharPrinter 类的实例作为参数传递给它们。然后我们调用 start() 方法启动这两个线程。

当我们运行这个程序时,它将会同时打印出字符 A 和 B,每个字符打印 10 次

Java 编写创建线程giveChar

原文地址: https://www.cveoy.top/t/topic/fKQg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录