1、Thread和Runnable的区别
Runnable更加面向对象。它把执行者和任务分开独立对象。
2、线程通信
把互斥、相互通信的逻辑任务放在同一个任务中更容易实现。如:
package com.skydream.traditional.thread.communication;
public class Task {
private boolean flag = true;
public void print1() throws InterruptedException {
synchronized (this) {
while (flag) {
this.wait();
}
for (int i = 0; i < 10; i++) {
System.out.println("This is the 10 loop " + i);
}
flag = true;
this.notifyAll();
}
}
public void print2() throws InterruptedException {
synchronized (this) {
while (!flag) {
this.wait();
}
for (int i = 0; i < 50; i++) {
System.out.println("50 loops " + i);
}
flag = false;
this.notifyAll();
}
}
}
final Task objTask = new Task();
new Thread(new Runnable() {
public void run() {
try {
while (true)
objTask.print2();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
while (true) {
objTask.print1();
}
3、wait ,notify必须在synchronized代码块中,切他们的所对象相同。
synchronized (this) {
while (!flag) {
this.wait();
}
for (int i = 0; i < 50; i++) {
System.out.println("50 loops " + i);
}
flag = false;
this.notifyAll();
}
都使用的this。