这一章节我们来讨论一下使用构造器或者内部类来实现多线程的编码变体。
1.基础实现
package com.ray.ch17; public class Test { public static void main(String[] args) { Thread thread1 = new ExtendsThread(); thread1.start(); Thread thread2 = new Thread(new ImplRunnable()); thread2.start(); } } class ExtendsThread extends Thread { @Override public void run() { System.out.println("ExtendsThread"); } } class ImplRunnable implements Runnable { @Override public void run() { System.out.println("ImplRunnable"); } }
输出:
ExtendsThread
ImplRunnable
2.使用构造器隐藏Thread的启动
package com.ray.ch17; public class Test { public static void main(String[] args) { new ExtendsThread(); new ImplRunnable(); } } class ExtendsThread extends Thread { public ExtendsThread() { start(); } @Override public void run() { System.out.println("ExtendsThread"); } } class ImplRunnable implements Runnable { public ImplRunnable() { new Thread(this).start(); } @Override public void run() { System.out.println("ImplRunnable"); } }
输出:
ExtendsThread
ImplRunnable
3.使用内部类隐藏多线程的扩展
package com.ray.ch17; public class Test { public static void main(String[] args) { new ExtendsThread(); new ImplRunnable(); } } class ExtendsThread { public ExtendsThread() { new Inner(); } private class Inner extends Thread { public Inner() { start(); } @Override public void run() { System.out.println("ExtendsThread"); } } } class ImplRunnable { public ImplRunnable() { new Inner(); } private class Inner implements Runnable { public Inner() { new Thread(this).start(); } @Override public void run() { System.out.println("ImplRunnable"); } } }
输出:
ExtendsThread
ImplRunnable
总结:这一章节主要讨论了使用构造器或者内部类来实现多线程的编码变体。
这一章节就到这里,谢谢。
-----------------------------------
时间: 2024-10-10 10:12:32