我们想要实现线程的交替运行,以下为示例
package demo;
public class ThreadBadDemo {
static int count = 0;
public static void main(String[] args) {
//实现主线程和线程交替执行 新手版
//更好示例请见ThreadGoodDemo 更加面向对象和可维护性
new Thread() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (ThreadBadDemo.class) {
for (int i = 0; i < 2; i++) {
System.out.println("子线程" + (count++));
}
ThreadBadDemo.class.notify();
try {
ThreadBadDemo.class.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}.start();
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (ThreadBadDemo.class) {
for (int i = 0; i < 2; i++) {
System.out.println("主线程----" + (count++));
}
ThreadBadDemo.class.notify();
try {
ThreadBadDemo.class.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
为了更加面向对象和体现内聚性(实现线程同步的代码集中在类中,在任意线程里使用该类的方法都是同步的)
package demo;
public class ThreadGoodDemo {
static boolean isRun = true;
public static void main(String[] args) throws InterruptedException {
// 实现主线程和线程交替执行
//实现内部同步方法Business类
final Business business = new Business();
//开始线程
new Thread() {
@Override
public void run() {
while (isRun) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
business.sub();
}
}
}.start();
//主线程
while (isRun) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
business.main();
}
}
static class Business {
boolean threadSub = true;
public synchronized void sub() {
while (threadSub) {//使用while 不用if 可以再次判断
try {
this.wait();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 0; i < 2; i++) {
System.out.println("sub thread " + i);
}
threadSub = true;
this.notify();
}
public synchronized void main() {
while (!threadSub) {//使用while 不用if 可以再次判断更安全
try {
this.wait();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 0; i < 2; i++) {
System.out.println("main thread ----" + i);
}
threadSub = false;
this.notify();
}
}
}