我是Java編程的新手,我想在線程的構造函數中傳遞一個整數值作爲參數。誰能幫我?如下圖所示我的代碼:在java中的線程構造函數中傳遞int值作爲參數
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對象啓動Thread。請閱讀一個基本的線程教程,因爲如果你只是付出一點努力,你會立即看到如何解決這個問題。 – 2012-03-24 04:16:10
你能通過代碼告訴我嗎? – 2012-03-24 07:19:16