gpt4 book ai didi

java - 线程无法正常工作?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:35:43 27 4
gpt4 key购买 nike

正在处理线程问题,我不确定这是否应该是这样,或者我是否编码不正确。据我了解,线程应该有多种方法同时进行,因此它们应该交织在一起。我的代码应该采用一个字符并重复 1000 次,但不是有两个字母的不同变体,而是“a”一千次,然后是“b”一千次。我的问题是什么?

主要方法

import java.util.*;
public class MainThread {

public static void main(String[] args) {
// TODO Auto-generated method stub

Scanner answer = new Scanner(System.in);

System.out.println("Give me a single character: ");
char h = answer.next().charAt(0);
System.out.println("Give me another single character: ");
char a = answer.next().charAt(0);

MyThread t1 = new MyThread(h);
MyThread t2 = new MyThread(a);

t1.start(h);
t2.start(a);

answer.close();
}
}

我的线程类

import java.util.*;
public class MyThread extends Thread{

Scanner answer = new Scanner(System.in);

public MyThread(char x) {
// TODO Auto-generated constructor stub
}


public void Stored(char x){
System.out.println("Type a single letter here: ");
}


//modified run method
public void start(char x){

for(int i = 0; i < 1000; i++){
System.out.print(x);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread.yield();
}
}
}

最佳答案

您所做的不是多线程,而是顺序调用了 start 方法,即,为了并行运行多个线程,您需要覆盖 run() 方法在你的 MyThread 类中。

重要的一点是run()方法会在你启动Thread时被JVM自动调用,而里面的代码run() 将与主线程/其他线程并行执行,因此在 MyThread 类中覆盖 run() 如下所示:

class MyThread extends Thread {

private char x;

public MyThread(char x) {
this.x= x;
}

// Add run() method
public void run() {

for (int i = 0; i < 10; i++) {
System.out.print(x);
try {
Thread.sleep(500);
} catch (InterruptedException e) {

e.printStackTrace();
}
Thread.yield();
}
}
}

主线程类:

public class MainThread {

public static void main(String[] args) {
// TODO Auto-generated method stub

Scanner answer = new Scanner(System.in);

System.out.println("Give me a single character: ");
char h = answer.next().charAt(0);
System.out.println("Give me another single character: ");
char a = answer.next().charAt(0);

MyThread t1 = new MyThread(h);
MyThread t2 = new MyThread(a);

t1.start();//this calls run() of t1 automatically
t2.start();//this calls run() of t2 automatically

answer.close();
}
}

我建议你看看here了解如何创建和启动 Thread 以及多线程的工作原理。

关于java - 线程无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43022225/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com