public class Demo extends Thread { private xx; public void run() { //这个线程要执行的东西 ....... } public static void main(String []__) { Demo th=new Demo(); th.start(); } }
这样就算是创建了一个线程
两个方法介绍
class A extends Runnable { private int age;//共同的field public void run() { .... } public static void main(String[]__) { A paremeter = new A(); Thread test=new Thread(paremeter); test.start(); Thread other=new Thread(paremeter); other.start(); //如果我们的run里面对于共享的变量age做出了修改,其实这两个线程中,field是相同的,可能会造成共享的数据出现访问冲突,可以考虑使用volatile关键字 } }
步骤如下:
package thread; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class CallableDemo implements Callable<Integer> { @Override public Integer call() throws Exception { int i=0; for(;i<99;i++) { System.out.println(i+" "+Thread.currentThread().getName()); } return i; } public static void main(String[]__) { //创建callable对象 CallableDemo rt=new CallableDemo(); //把callable绑定到FutureTask对象上面 FutureTask<Integer> task=new FutureTask<>(rt); //把任务加入thread的target中去 new Thread(task).start(); try { System.out.println(task.isDone()+" "+task.get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } new Thread(task).start(); try { System.out.println(task.isDone()+" "+task.get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } //他们的field也是只有一块,一个线程跑完会修改field中的数值 } }
优点:
缺点:
new Thread(new Runnable() { private int i=0; @Override public void run() { System.out.println(i); } },String.valueOf("1")).start();
优点:
缺点: