1.用两种方式实现两个线程,一个线程负责打印1-2600,另一个线程打印A-Z,反复打印100遍

用java
2024-12-16 22:27:43
推荐回答(3个)
回答1:

public class ThreadTest {
class T1 extends Thread {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
for (int j = 1; j <= 2600; j++) {
System.out.println(j);
}
}
}
}

class T2 implements Runnable {
char[] c = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();

@Override
public void run() {
for (int i = 0; i < 100; i++) {
for (int j = 0; j < c.length; j++) {
System.out.println(c[j]);
}
}
}
}

public void test() {
Thread t1 = new T1();
Thread t2 = new Thread(new T2());
t1.start();
t2.start();
}

public static void main(String[] args) {
ThreadTest threadTest = new ThreadTest();
threadTest.test();
}
}

//最好将线程T1打印改成1-26,要不然你不太容易看到多线程效果。

回答2:

第一种:extends Thread

package comparableDemo1;
public class bb{
public static void main(String[] args) {
Thread t1 = new SubFThread();
Thread t2 = new SubSThread();
t1.start();
t2.start();
}
}
class SubFThread extends Thread{
public void run(){
for(int i =0;i<=2600;i++){
System.out.println("我是第一个线程"+i);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread.yield();
}
}
}
class SubSThread extends Thread{
public void run(){
while(true){
for(char i = 'A';i<='Z';i++){
System.out.println("我是第二个线程"+i);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread.yield();
}
}
}
}

第二种:
package comparableDemo1;

public class bb {
public static void main(String[] args) {
new Thread(new Runnable() {
public void run() {
for (int i = 0; i <= 2600; i++) {
System.out.println("我是第一个线程" + i);
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {

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

new Thread(new Runnable() {
public void run() {

while (true) {
for (char i = 'A'; i <= 'Z'; i++) {
System.out.println("我是第二个线程" + i);

try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {

e.printStackTrace();
}
}
}
}
}).start();
}
}

回答3:

一种方法是继承Thread类
一种是实现Runnable接口
两种都是开启两个线程即可,没什么特殊要求,不用加同步锁