运维开发网

centos7.x设置SSH免密码登陆

运维开发网 https://www.qedev.com 2020-05-08 14:44 出处:网络 作者:运维开发网整理
Java多线程实现的方式有四种 1.继承Thread类,重写run方法 2.实现Runnable接口,重写run方法,实现Runnable接口的实现类的实例对象作为Thread构造函数的target

Java多线程实现的方式有四种

  • 1.继承Thread类,重写run方法
  • 2.实现Runnable接口,重写run方法,实现Runnable接口的实现类的实例对象作为Thread构造函数的target
  • 3.通过Callable和FutureTask创建线程
  • 4.通过线程池创建线程

方式1:继承Thread类:

public class ThreadOne extends Thread{ public ThreadOne(){ } public void run(){ System.out.println(Thread.currentThread().getName()); } public static void main(String[] args){ ThreadOne threadOne = new ThreadOne(); threadOne.setName("继承Thread的方式实现线程"); threadOne.start(); System.out.println(Thread.currentThread().toString()); } }
分享图片方式2:通过实现Runnable接口 :
public class ThreadTwo { public static void main(String[] args){ System.out.println(Thread.currentThread().getName()); Thread t1 = new Thread(new MyThread()); t1.start(); } } class MyThread implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()+"-->通过实现接口的方式实现线程"); } }

方式3:通过Callable和FutureTask创建线程 

public class ThreadThree { public static void main(String[] args) { Callable<Object> callable = new Tickets<Object>(); FutureTask<Object> task = new FutureTask<Object>(callable); Thread t = new Thread(task); System.out.println(Thread.currentThread().getName()); t.start(); } }  class Tickets<Object> implements Callable<Object>{ @Override public Object call() throws Exception { System.out.println(Thread.currentThread().getName()+"-->通过实现Callable接口通过FutureTask包装器来实现的线程"); return null; } }

方式4:通过线程池创建线程

public class ThreadFour{ private static int POOL_NUM = 10; public static void main(String[] args) throws InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool(5); for(int i = 0; i<POOL_NUM; i++) { RunnableThread thread = new RunnableThread(); executorService.execute(thread); }  executorService.shutdown(); } } class RunnableThread implements Runnable { @Override public void run(){ System.out.println("通过线程池方式创建的线程:" + Thread.currentThread().getName()); } }  
分享图片
0

精彩评论

暂无评论...
验证码 换一张
取 消