使用线程作为对象

Cal*_*ebB 2 java oop multithreading object

我如何使用线程作为对象?我试图这样做.

对象类

public class Object implements Runnable{
public String name = "";
public void run(){
  //logic code here
}
}
Run Code Online (Sandbox Code Playgroud)

我这样称呼它.

Thread contract1 = new Thread(new Object());
    contract1.name = "foo";
    contract1.start();
Run Code Online (Sandbox Code Playgroud)

我收到了错误

The field Thread.name is not visible
Run Code Online (Sandbox Code Playgroud)

什么是最有资源的方法来做到这一点,并需要最短的代码量?

谢谢.

Epi*_*rce 5

public class YourRunnable implements Runnable{
   private String name;

   public YourRunnable(String name) {
       this.name = name;
   }

   public void run() {
      //logic code here
   }
}
Run Code Online (Sandbox Code Playgroud)

然后

Thread contract1 = new Thread(new YourRunnable("foo"));
contract1.start();
Run Code Online (Sandbox Code Playgroud)

所以使用构造函数.

编辑:但要做你想做的事,你所要做的就是

public class YourRunnable implements Runnable{
   public String name;

   public void run() {
      //logic code here
   }
}
Run Code Online (Sandbox Code Playgroud)

然后

YourRunnable yourRunnable = new YourRunnable();
Thread contract1 = new Thread(yourRunnable);
yourRunnable.name = "foo";
contract1.start();
Run Code Online (Sandbox Code Playgroud)