join测试
package lmlc.test;
public class TestJoin {
public static void main(String args[]) {
Myrunner mr = new Myrunner();
Thread t = new Thread(mr);
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i =0;i<50;i++) {
System.out.println("main" + i);
}
}
}
class Myrunner implements Runnable {
public void run() {
for (int i=0;i<50;i++) {
System.out.println("subthread " + i);
}
}
}
先将上面的join删除,看到输出,主线程与子线程的执行是重叠的,添加join后,子线程先执行,执行完成后在执行主线程的。
为了在多线程的情况下,每个线程在执行一段代码的是能,能顺序执行,使用synchronized
摘自:
http://blog.csdn.net/xiao__gui/article/details/8188833
package lmlc.test;
class Sync {
public void test() {
synchronized (this) {
System.out.println("test开始..");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test结束..");
}
}
}
class MyThread extends Thread {
private Sync sync;
public MyThread(Sync sync) {
this.sync=sync;
}
public void run() {
sync.test();
}
}
public class Main {
public static void main(String[] args) {
Sync sync = new Sync();
for (int i = 0; i < 3; i++) {
Thread thread = new MyThread(sync);
thread.start();
}
}
}
这2个组合是在同步方法块中使用,被锁定的对象调用wait方法,当前线程被阻塞并放弃该对象的互斥锁,其他线程可以有机会获得执行机会,调用wait被阻塞的线程,会被添加到一个特殊的对象等待队列中,直到调用wait方法的对象在其他的线程中调用notify或notifyall方法
package cn.javass.c13;
public class WaitReleaseLock {
public static void main(String[] args) {
ThreadA4 ta = new ThreadA4(true);
Thread b = new Thread(ta);
Thread a = new Thread(ta);
b.start();
a.start();
}
}
class ThreadA4 implements Runnable {
private boolean needWait = false;
public ThreadA4(boolean needWait) {
this.needWait = needWait;
}
public void run() {
synchronized (this) {
for (int i = 0; i < 10; i++) {
System.out
.println(Thread.currentThread().getName() + ",i=" + i);
try {
if (needWait) {
this.needWait = false;
wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//this.notify();
}
}
}
这个例子中把notify注释掉,导致线程一直等待,挂在那里了。