Java语言的关键字synchronized,当它用来修饰一个方法或者一个代码块的时候,能够保证在同一时刻最多只有一个线程执行该段代码。
线程有6种状态:新建,运行(可运行),阻塞,等待,即使等待,终止。
/**
* 在这里给出对类 ThreadState 的描述。
*
* @作者(你的名字)
* @版本(一个版本号或者一个日期)
*/
public class ThreadState implements Runnable
{
public synchronized void waitForASecond()throws InterruptedException{
wait(500);
}
public synchronized void waitForYears() throws InterruptedException{
wait();
}
public synchronized void notifyNow() throws InterruptedException{
notify();
}
public void run(){
try{
waitForASecond();
waitForYears();
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
/**
* 在这里给出对类 Test 的描述。
*
* @作者(你的名字)
* @版本(一个版本号或者一个日期)
*/
public class Test
{
// 实例变量 - 用你自己的变量替换下面的例子
private int x;
public static void main(String[]args)throws InterruptedException{
ThreadState state=new ThreadState();
Thread thread=new Thread(state);
System.out.println("create new thread:"+thread.getState());
thread.start();
System.out.println("start new thread:"+thread.getState());
Thread.sleep(100);
System.out.println("jishi wait:"+thread.getState());
Thread.sleep(1000);
System.out.println("wait thread:"+thread.getState());
state.notifyNow();
System.out.println("call thread:"+thread.getState());
Thread.sleep(1000);
System.out.println("end thread:"+thread.getState());
}
/**
* 类 Test 的对象的构造函数
*/
public Test()
{
// 初始化实例变量
x = 0;
}
/**
* 一个方法的例子 - 使用你自己的说明替代它
*
* @参数 y,方法的一个样本参数
* @返回 x,y的和
*/
public int sampleMethod(int y)
{
// 在这里加入你的代码
return x + y;
}
}
浙公网安备 33010602011771号