线程的start方法剖析:模版设计模式在Thread中的应用
Thread start 方法源码分析以及注意事项
public synchronized void start() {if (threadStatus != 0)throw new IllegalThreadStateException();group.add(this);boolean started = false;try {start0();started = true;} finally {try {if (!started) {group.threadStartFailed(this);}} catch (Throwable ignore) {}}}
private native void start0();
※ Causes this thread to begin execution; the Java Virtual Machine calls the <code>run</code> method of this thread.
Thread 被构造后的 NEW 状态,事实上 threadStatus 这个内部属性为0。
不能两次启动 Thread,否则就会出现 IllegalThreadStateException 异常。
线程启动后将会被加入到一个 ThreadGroup 中,后文中我们将详细介绍 ThreadGroup。
一个线程生命周期结束,也就是到了 TERMINATED 状态,再次调用 start 方法是不允许的,也就是说 TERMINATED 状态是没有办法回到 RUNNABLE/RUNNING 状态的。
Thread thread = new Thread(){@Overridepublic void run(){try{TimeUnit.SECONDS.sleep(10);} catch (InterruptedException e){e.printStackTrace();}}};thread.start();//启动线程thread.start();//再次启动
Thread thread = new Thread(){@Overridepublic void run(){try{TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e){e.printStackTrace();}}};thread.start();TimeUnit.SECONDS.sleep(2);//休眠主要是确保 thread 结束生命周期thread.start();//企图重新激活该线程
模板设计模式在 Thread 中的应用
@Overridepublic void run() {if (target != null) {//我们并没有使用 runnable 构造 Threadtarget.run();}}
public class TemplateMethod {public final void print(String message) {System.out.println("################");wrapPrint(message);System.out.println("################");}protected void wrapPrint(String message) {}public static void main(String[] args) {TemplateMethod t1 = new TemplateMethod(){@Overrideprotected void wrapPrint(String message) {System.out.println("*"+message+"*");}};t1.print("Hello Thread");TemplateMethod t2 = new TemplateMethod(){@Overrideprotected void wrapPrint(String message) {System.out.println("+"+message+"+");}};t2.print("Hello Thread");}}
Thread 模拟营业大厅叫号机程序
public class TicketWindow extends Thread {//柜台名称private final String name;//最多受理50笔业务private static final int MAX = 50;private int index = 1;public TicketWindow(String name) {this.name = name;}@Overridepublic void run() {while (index <= MAX) {System.out.println("柜台:" + name + "当前的号码是:" + (index++));}}}
public static void main(String[] args) {TicketWindow ticketWindow1 = new TicketWindow("一号出号机");ticketWindow1.start();TicketWindow ticketWindow2 = new TicketWindow("二号出号机");ticketWindow2.start();TicketWindow ticketWindow3 = new TicketWindow("三号出号机");ticketWindow3.start();TicketWindow ticketWindow4 = new TicketWindow("四号出号机");ticketWindow4.start();}
public class TicketWindow extends Thread {private final String name;private static final int MAX = 50;private static int index = 1;public TicketWindow(String name) {this.name = name;}@Overridepublic void run() {while (index <= MAX) {System.out.println("柜台:" + name + "当前的号码是:" + (index++));}}}
Runable接口的引入以及策略模式在Thread中的使用
Runnable 的职责
public interface Runnable {void run();}
@Overridepublic void run() {//如果构造 Thread 时传递了 Runnable,则会执行 runnable 的 run 方法if (target != null) {target.run();}//否则需要重写 Thread 类的 run 方法}
策略模式在 Thread 中的应用
import java.sql.ResultSet;public interface RowHandler<T>{T handle(ResultSet rs);}
import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;public class RecordQuery{private final Connection connection;public RecordQuery(Connection connection){this.connection = connection;}public <T> T query(RowHandler<T> handler, String sql, Object... params)throws SQLException{try (PreparedStatement stmt = connection.prepareStatement(sql)){int index = 1;for (Object param : params){stmt.setObject(index++, param);}ResultSet resultSet = stmt.executeQuery();return handler.handle(resultSet);//①调用RowHandler}}}
模拟营业大厅叫号机程序
public class TicketWindowRunnable implements Runnable {private int index = 1;//不做 static 修饰private final static int MAX = 50;@Overridepublic void run() {while (index <= MAX) {System.out.println(Thread.currentThread() + " 的号码是:" + (index++));try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}}}}
public static void main(String[] args) {final TicketWindowRunnable task = new TicketWindowRunnable();Thread windowThread1 = new Thread(task, "一号窗口");Thread windowThread2 = new Thread(task, "二号窗口");Thread windowThread3 = new Thread(task, "三号窗口");Thread windowThread4 = new Thread(task, "四号窗口");windowThread1.start();windowThread2.start();windowThread3.start();windowThread4.start();}
文章转载自Alleria Windrunner,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




