多线程
线程生命周期:new→start()→run()→sleep(),wait()→dead
1、线程同步,thread synchronization:当多个线程需要使用同一个资源时,有可能造成结果紊乱。需要使用同步的方法来使某一时刻,某一资源只被一个线程使用。java中每一个object都与一个monitor联系起来,线程将锁住或解锁monitor。一个object的monitor每次只有一个thread可以对其加锁。java使用synchronized对线程共享的资源进行分配,当某一线程锁住共享资源时,只有当该线程完成时才把共享资源解锁,并将锁交给下一个需要使用共享资源的线程。
class PrintDemo {
public void printCount(){
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
PrintDemo PD;
ThreadDemo( String name, PrintDemo pd){
threadName = name;
PD = pd;
}
public void run() {
synchronized(PD) {
PD.printCount();
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start ()
{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
PrintDemo PD = new PrintDemo();
ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );
T1.start();
T2.start();
// wait for threads to end
try {
T1.join();
T2.join();
} catch( Exception e) {
System.out.println("Interrupted");
}
}
}
输出结果:
Starting Thread - 1
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 1 exiting.
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.
wait(): 暂停当前线程,进入另一个需要使用该对象为共享资源的线程;
notify(): 唤醒一个被暂停的线程。
class Chat {
boolean flag = false;
int sum = 0;
public synchronized void Question(String msg) {
if (flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Question: sum ="+this.sum+", "+msg);
flag = true;
notify();
}
public synchronized void Answer(String msg) {
if (!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Answer: sum ="+this.sum+", "+msg);
flag = false;
notify();
}
}
class T1 implements Runnable {
Chat m;
String[] s1 = { "Hi", "How are you ?", "I am also doing fine!" };
public T1(Chat m1) {
this.m = m1;
new Thread(this, "Question").start();
}
public void run() {
for (int i = 0; i < s1.length; i++) {
m.Question(s1[i]); //Question方法被同步化了
m.sum++; //该sum没有被同步化,sum值被共同修改
}
}
}
class T2 implements Runnable {
Chat m;
String[] s2 = { "Hi", "I am good, what about you?", "Great!" };
public T2(Chat m2) {
this.m = m2;
new Thread(this, "Answer").start();
}
public void run() {
for (int i = 0; i < s2.length; i++) {
m.Answer(s2[i]);
m.sum++;
}
}
}
public class ThreadCommunication {
public static void main(String[] args) {
Chat m = new Chat();
new T1(m);
new T2(m);
}
}
输出结果:
Question: sum = 0, Hi
Answer: sum = 1, Hi
Question: sum = 2, How are you ?
Answer: sum = 3, I am good, what about you?
Question: sum = 4, I am also doing fine!
Answer: sum = 5, Great!