http://www.ibm.com/developerworks/cn/java/multithreading/
http://www.ibm.com/developerworks/cn/java/j-concurrent/
import java.util.*; class TimePrinter extends Thread { int pauseTime; String name; public TimePrinter(int x, String n) { pauseTime = x; name = n; } public void run() { while(true) { try { System.out.println(name + ":" + new Date(System.currentTimeMillis())); Thread.sleep(pauseTime); } catch(Exception e) { System.out.println(e); } } } static public void main(String args[]) { TimePrinter tp1 = new TimePrinter(1000, "Fast Guy"); tp1.start(); TimePrinter tp2 = new TimePrinter(3000, "Slow Guy"); tp2.start(); } }
一个具体的类,封装了线程的行为。
要创建一个线程,必须创建一个从Thread类导出的新类。必须覆盖Thread的run()函数来完成有用的工作,用户并不直接调用此函数,必须调用Thread的start(),该函数再调用run()
import java.util.*; class TimePrinter implements Runnable { int pauseTime; String name; public TimePrinter(int x, String n) { pauseTime = x; name = n; } public void run() { while(true) { try { System.out.println(name + ":" + new Date(System.currentTimeMillis())); Thread.sleep(pauseTime); } catch(Exception e) { System.out.println(e); } } } static public void main(String args[]) { Thread t1 = new Thread (new TimePrinter(1000, "Fast Guy")); t1.start(); Thread t2 = new Thread (new TimePrinter(3000, "Slow Guy")); t2.start(); } }
引言:简单方式利用线程,只有最小的数据流
并发——不同的线程访问同一个对象时。
(锁 是每个对象都有的,是java.lang.Object类提供的吧)
public class Account { String holderName; float amount; public Account(String name, float amt) { holderName = name; amount = amt; } public void deposit(float amt) { amount += amt; } public void withdraw(float amt) { amount -= amt; } public float checkBalance() { return amount; } }
public class Account { String holderName; float amount; public Account(String name, float amt) { holderName = name; amount = amt; } public synchronized void deposit(float amt) { amount += amt; } public synchronized void withdraw(float amt) { amount -= amt; } public float checkBalance() { return amount; } }
线程组:对线程进行归类管理,以便于调试和监视。具体操作上,只有在创建线程的同时将它与一个线程组相关联。在使用大量线程的程序中,使用线程组有很大帮助,可以将它们看做是计算机上的目录和文件结构。
线程间发信:考虑到线程在执行过程中需要一定的条件,仅使用防止并发的synchronized关键字是不够的,它没有实现线程间发信。Object类提供了三个函数(锁是Object提供的,在线程通信后需要一些切换那就需要对锁进行加上或者解除操作。)wait()、notify()、notifyAll()
public class BSync { int totalThreads; int currentThreads; public BSync(int x) { totalThreads = x; currentThreads = 0; } public synchronized void waitForAll() { currentThreads++; if(currentThreads < totalThreads) { try { wait(); } catch (Exception e) {} } else { currentThreads = 0; notifyAll(); } } }
详细:http://blog.csdn.net/garybrother/archive/2009/03/29/4033447.aspx