關於線程:
java
在java中,Thread類表明一個線程。安全
實現線程的方式有兩種: 見下面的Thread.java 和 MyRunnable.javaide
繼承thread類,重寫run()方法線程
public class ThreadTest { /** * 練習: 不考慮線程安全的問題, * 啓用兩個線程共同打印0~99 */ public static void main(String[] args) { //1.建立線程對象 Thread thread = new FirstThread("FirstThread"); //2.調用start()方法啓動線程 thread.start(); String threadName = Thread.currentThread().getName(); for (int i = 0; i < 100; i++) { System.out.println(threadName + ": " + i); } } } class FirstThread extends Thread { public FirstThread(String threadName) { super(threadName); } /** * 線程體在run()方法中 */ @Override public void run() { for (int i = 0; i < 100; i++) { String threadName = Thread.currentThread().getName(); System.out.println(threadName + ": " + i); } } }
b. 實現Runnable接口,重寫run()方法code
public class MyRunnable implements Runnable { private int i = 0; @Override public void run() { for (; i < 100; i++) { System.out.println(Thread.currentThread().getName() + ": " + i); } } public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); Thread thread1 = new Thread(myRunnable); Thread thread2 = new Thread(myRunnable); thread1.start(); thread2.start(); } }
3. 啓動線程調用線程的start()方法。對象