一 線程的基本概念
線程是一個程序內部的順序控制流
二 線程的創建和啟動
可以有兩種方式創建新的線程:
第一種:
第二種:
class MyThread extends Thread {
public void run() {
}
MyThread myThread = new MyThread();
三 線程控制的基本方法
isAlive():判斷線程是否還
getPriority():獲得線程的優先級數值
setPriority():設置線程的優先級數值
Thread
join():調用某線程的該方法
yield():讓出cpu
wait():當前線程進入對象的wait pool
notify()/notifyAll():喚醒對象的wait pool中的一個/所有等待線程
四 線程同步
實現生產者消費者問題來說明線程問題
/**
* 生產者消費者問題
*/
package com
/**
* @author johnston
*
* @version
*/
public class ProducerConsumer {
/**
* @param args
*/
public static void main(String[] args) {
ProductBox pb = new ProductBox();
Producer p = new Producer(pb);
Consumer c = new Consumer(pb);
Thread pThread = new Thread(p);
Thread cThread = new Thread(c);
pThread
pThread
cThread
}
}
/**
* 產品對象
* @author johsnton
*/
class Product {
int id;
public Product(int id) {
super();
this
}
public String toString(){
return
}
}
/**
* 產品盒對象
* @author johnston
*/
class ProductBox {
Product[] productbox = new Product[
int index =
public ProductBox() {
super();
}
public synchronized void push(Product p) {
while (index == productbox
try {
this
} catch (InterruptedException e) {
// TODO Auto
e
}
}
this
productbox[index] = p;
index ++;
}
public synchronized Product pop() {
while (index ==
try {
this
} catch (InterruptedException e) {
// TODO Auto
e
}
}
this
index
return productbox[index];
}
}
/**
* 生產者
* @author johnston
*/
class Producer implements Runnable {
ProductBox productbox = null;
public Producer(ProductBox productbox) {
super();
this
}
@Override
public void run() {
// TODO Auto
for (int i=
Product p = new Product(i);
productbox
System
try {
Thread
} catch (InterruptedException e) {
e
}
}
}
}
/**
* 消費者
* @author johnston
*/
class Consumer implements Runnable {
ProductBox productbox = null;
public Consumer(ProductBox productbox) {
super();
this
}
@Override
public void run() {
// TODO Auto
for (int i=
Product p = productbox
System
try {
Thread
} catch (InterruptedException e) {
e
}
}
}
}
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27546.html