1. 程式人生 > >對 JAVA 多執行緒的理解

對 JAVA 多執行緒的理解

所謂多執行緒,就是計算機同時做幾件事,對外表現的是同時完成。

實現方法

在 JAVA 中就非常比較簡單的了,只需要將新建的類實現 runable 方法,在類中的 run 方法中寫自己要完成的事情。

一個例子

package com.mingsoft;

import java.text.SimpleDateFormat;
import java.util.Date;

public class TestThread3 {
    public static void main(String args[]) {
        Counter c1 = new Counter(1
); Thread t1 = new Thread(c1); Thread t2 = new Thread(c1); Thread t3 = new Thread(c1); Counter c2 = new Counter(2); Thread t4 = new Thread(c2); Thread t5 = new Thread(c2); Thread t6 = new Thread(c2); TimeDisplay timer = new TimeDisplay(); Thread t7 = new
Thread(timer); t1.start(); //t2.start(); //t3.start(); t4.start(); //t5.start(); //t6.start();*/ t7.start(); } } class Counter implements Runnable{ int id; public Counter(int id ) { // TODO Auto-generated constructor stub this
.id = id; } public void run() { int i = 0; while (i++ <= 10) { System.out.println("ID: " + id + " No. " + i); try { Thread.sleep(10); } catch (InterruptedException e) { // TODO: handle exception } } } } class TimeDisplay implements Runnable{ public void run() { int i = 0; while (i++ <=3) { System.out.println( new SimpleDateFormat().format(new Date())); try { Thread.sleep(40); } catch (InterruptedException e) { // TODO: handle exception } } } }

就實現了多執行緒問題