我想從java.lang.Runnable實現Runnable的類的對象創建線程,但它不工作。使用Runnable對象創建線程
[email protected]:~/Desktop/java_prog$ javac Runnable.java
Runnable.java:27: error: no suitable constructor found for Thread(counter,String)
Thread td=new Thread(obj,"bac");
^
constructor Thread.Thread(Runnable,AccessControlContext) is not applicable
(argument mismatch; counter cannot be converted to Runnable)
constructor Thread.Thread(ThreadGroup,Runnable) is not applicable
(argument mismatch; counter cannot be converted to ThreadGroup)
constructor Thread.Thread(ThreadGroup,String) is not applicable
(argument mismatch; counter cannot be converted to ThreadGroup)
constructor Thread.Thread(Runnable,String) is not applicable
(argument mismatch; counter cannot be converted to Runnable)
Note: Some messages have been simplified; recompile with - Xdiags:verbose to get full output
1 error
這是錯誤。 代碼如下.........
import java.io.*;
interface Runnable{
public void run();
}
class counter implements Runnable {
Thread t=Thread.currentThread();
private int x;
public counter(){x=0;}
public int getval(){return x;}
public void run()
{
try{
while(x<5){
System.out.println(t.getName()+ ":" + (x++));
Thread.sleep(250);
}
System.out.println("Exit from thread:"+t);}
catch(InterruptedException e){
System.out.println("InterruptedException");
}
}
}
class client {
public static void main(String args[])
{
counter obj=new counter();
Thread td=new Thread(obj,"bac");
td.start();
int val;
try{
do{
val=obj.getval();
System.out.println(td.getName()+ ":" + val);
val=6;
Thread.sleep(1000);
}while(val<5);
}
catch(InterruptedException e)
{
System.out.println("InterruptedException 2");
}
System.out.println("Exit from thread:"+td.getName());
}
}
我是不是要創建任何線程構造函數? 或我可以從java.lang庫訪問Runnable類? 這裏有什麼問題?
第一種:已經存在預定義的接口Runnable。不要覆蓋預定義的名稱。然後。你在超級基本的東西上遇到了麻煩......你最好退後一步,在思考線程之前先處理更簡單的例子。對不起,但你的代碼是一大堆錯誤。 – GhostCat
好的。我會改進它。 –