【发布时间】:2012-03-24 04:13:17
【问题描述】:
我是 Java 编程新手,我想在线程的构造函数中传递一个整数值作为参数。谁能帮我?我的代码如下所示:
import java.io.*;
import java.lang.Thread;
import java.util.Scanner;
class A implements Runnable {
int count;
int a;
Thread t;
A(int i) {
synchronized (this) {
a = i;
// count=Integer.parseInt(a);
count = a;
t = new Thread(this);
t.start();
}
}
@Override
public void run() {
inc();
}
public synchronized void inc() {
try {
if (count != 0) {
synchronized (this) {
++count;
System.out.println("Incrementing pre " + count);
// String p = String.valueOf(c);
// System.out.println("Incrementing in value of p " + p);
Thread.sleep(2000);
// int cminus = count-1;
// --count;
new B(count);
// String p = String.valueOf(cplus);
// System.out.println("Incrementing in p " + cplus);
}
} else {
System.out.println("Count values cannot be negative");
}
}
catch (InterruptedException e) {
// ...
}
}
}
class B implements Runnable {
int count;
int a;
Thread t;
B(int i) {
a = i;
// count=Integer.parseInt(a);
count = a;
t = new Thread(this);
t.start();
}
@Override
public void run() {
dec();
}
public synchronized void dec() {
try {
if (count != 0) {
synchronized (this) {
--count;
System.out.println("Decrementing first " + count);
// String p = String.valueOf(count);
// System.out.println("Value of p: " + count);
Thread.sleep(1000);
// ++count;
// System.out.println("p out" + p);
new A(count);
}
} else {
System.out.println("Count values cannot be negative");
}
} catch (InterruptedException e) {
// ...
}
}
}
class Thread_array extends Thread implements Runnable {
public static void main(String[] args) throws IOException,
InterruptedException {
int z;
System.out.print("Enter your desired number: ");
Scanner input = new Scanner(System.in);
int dj = input.nextInt();
int[] array = new int[dj];
for (z = 0; z < array.length; z++) {
array[z] = 0;
System.out.print(" " + array[z]);
}
System.out.println();
new B(dj);
new A(dj);
}
}
总而言之,我希望能够做到这一点:
t = new Thread(this, i);
而不是
t = new Thread(this);
谢谢。
【问题讨论】:
-
如果您甚至不打算使用 Runnable 类,为什么还要创建它?解决方案是使用 Runnable 的构造函数,然后使用 Runnable 对象启动线程。请阅读基本的线程教程,如果您稍加努力,您将立即看到如何解决这个问题。
标签: java multithreading