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());
}
}
iは、任意のスレッドのコンストラクタを作成する必要がありますか。? または、私はjava.langライブラリからRunnableクラスにアクセスしますか? ここに問題がありますか?
最初に、すでに定義済みのインタフェースRunnableが既に存在します。定義済みの名前は上書きしないでください。その後、あなたは超基本的なものに問題があります...もっと簡単な例に取りかかることをお勧めします。申し訳ありませんが、あなたのコードは間違いを完全に混乱させます。 – GhostCat
大丈夫です。私はそれを改善します。 –