根据一些资料整理如下:
一个程序中可以有多条执行线索同时执行,一个线程就是程序中的一条执行线索,每个线程上都关联有要执行的代码,即可以有多段程序代码同时运行,每个程序至少都有一个线程,即main方法执行的那个线程。
状态:就绪,运行,synchronize阻塞,wait和sleep挂起,结束。wait必须在synchronized内部调用。
调用线程的start方法后线程进入就绪状态,线程调度系统将就绪状态的线程转为运行状态,遇到synchronized语句时,由运行状态转为阻塞,当synchronized获得锁后,由阻塞转为运行,在这种情况可以调用wait方法转为挂起状态,当线程关联的代码执行完后,线程变为结束状态。
package thread;
public class MutiThread {
public static void main(String[] args) {
new Thread(new Thread1()).start();
try {
Thread.sleep(100);//让thread1休眠
} catch (Exception e) {
e.printStackTrace();
}
new Thread(new Thread2()).start();
}
private static class Thread1 implements Runnable{
@Override
public void run() {
//这里的thread1和thread2内部run方法要用同意对象作为监视器,不能用this,thread1的this和thread2的this不是同一个对象
synchronized (MutiThread.class) {
System.out.println("enter thread1");
System.out.println("thread1 is waiting");
try {
//thread1进入等待,并把自己的锁让出,等待别的线程调用notify方法
MutiThread.class.wait();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("thread1 is going on");
System.out.println("thread1 is being over");
}
}
}
private static class Thread2 implements Runnable{
@Override
public void run() {
synchronized(MutiThread.class){
System.out.println("enter thread2");
System.out.println("thread2 notify other thread");
//如果不唤醒,thread1就无法接着进行,该方法并不是立马让出锁,若是之后还有代码,需要执行完这些代码后才会释放锁
//告诉调用过wait方法的线程可以去参与获得锁的竞争
MutiThread.class.notify();
System.out.println("thread2 is sleeping");
try {
Thread.sleep(100);//sleep并没有让出锁,所以thread2接着进行,之后才轮到thread1,只是主动让出CPU
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("thread2 is going on");
System.out.println("thread2 is being over");
}
}
}
}
输出结果
enter thread1
thread1 is waiting
enter thread2
thread2 notify other thread
thread2 is sleeping
thread2 is going on
thread2 is being over
thread1 is going on
thread1 is being over