线程的创建
java线程创建一般有三种方法:
1)继承Thread方法,并重写run()方法
2)实现Runnable方法,并重写run()方法
3)实现callable方法,并重写call()方法。这种线程创建方式有返回值
进程的等待与通知
java中的任意对象都可以当做锁,我们只需要用synchronized关键字修饰即可。任何一个对象都有wait()方法,用于将拿到锁的线程挂起,并且有notify()和notifyAll()方法,用于唤醒该锁的阻塞队列中的线程,其中notify()方法用于唤醒一个线程,notifyAll()方法用于唤醒所有线程。
public class Threads {
private static volatile Object resourceA = new Object();
public static void main(String[] args) throws InterruptedException {
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
synchronized (resourceA) {
System.out.println("threadA get resourceA lock");
try {
System.out.println("threadA begin wait");
resourceA.wait();
System.out.println("threadA end wait");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
synchronized (resourceA) {
System.out.println("threadB get resourceA lock");
try {
System.out.println("threadB begin wait");
resourceA.wait();
System.out.println("threadB end wait");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread threadC = new Thread(new Runnable() {
@Override
public void run() {
synchronized (resourceA){
System.out.println("threadC begin notify");
resourceA.notify();
}
}
});
// 启动线程
threadA.start();
threadB.start();
Thread.sleep(1000);
threadC.start();
// 等待线程结束
threadA.join();
threadB.join();
threadC.join();
System.out.println("main over");
}
}
上面这段代码只是唤醒了一个线程,另一个线程会一直被阻塞。
我们将notify()换成notifyAll()后,就可以唤醒所有的线程了。
public class Threads {
private static volatile Object resourceA = new Object();
public static void main(String[] args) throws InterruptedException {
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
synchronized (resourceA) {
System.out.println("threadA get resourceA lock");
try {
System.out.println("threadA begin wait");
resourceA.wait();
System.out.println("threadA end wait");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
synchronized (resourceA) {
System.out.println("threadB get resourceA lock");
try {
System.out.println("threadB begin wait");
resourceA.wait();
System.out.println("threadB end wait");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread threadC = new Thread(new Runnable() {
@Override
public void run() {
synchronized (resourceA){
System.out.println("threadC begin notify");
resourceA.notifyAll();
}
}
});
// 启动线程
threadA.start();
threadB.start();
Thread.sleep(1000);
threadC.start();
// 等待线程结束
threadA.join();
threadB.join();
threadC.join();
System.out.println("main over");
}
}
以上代码来自《Java并发编程之美》