Java多线程传统实现方法

Java多线程传统实现方法

Java多线程的传统实现方法有两种:一种是继承Thread类并重写其run方法;另一种是实现Runnable接口,实现其run方法。

/** * 多线程的传统实现方法 * */{(String[] args) {/** 方法1:覆盖父类Thread的run方法*/Thread thread = new Thread() {() {while(true) {try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(“输出1:” + Thread.currentThread().getName());System.out.println(“输出2:” + this.getName());}}};thread.start();/** 方法2:实现Runnable接口,实现其run方法*/Thread thread2 = new Thread(new Runnable() {() {while(true) {try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(“输出1:” + Thread.currentThread().getName());//System.out.println(“输出2:” + this.getName());}}});thread2.start();/** 3:二者同时存在时的调用规则** 首先找子类的run方法,,* 若子类没有覆盖run方法,则找Runnable的run方法(参考jdk中Thread.run()的实现)* 因此本代码会执行子类覆盖的run方法*/new Thread(new Runnable(){() {while(true) {try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(“Runnable:” + Thread.currentThread().getName());}}}){() {while(true) {try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(“Thread:” + Thread.currentThread().getName());}}}.start();}}

思念是对昨天悠长的沉淀和对未来美好的向往。

Java多线程传统实现方法

相关文章:

你感兴趣的文章:

标签云: