线程存在的状态
新生状态:使用new新建的一个线程
就绪状态:的调用start()方法,cpu未赋予时间片时
阻塞状态:遇到阻塞事件
(sleep方法(不释放锁),join方法(加入线程),yield方法(暂停当前线程,让出cpu),cpu时间片结束线程未执行结束,暂时挂起),
阻塞结束后线程进入就绪状态
运行状态:cpu分配时间片,线程运行
等待状态:wait()方法,需调用notify()/notifyAll()方法解除,解除之后进入就绪状态
死亡状态:线程执行完毕/强制中断
阻塞状态分析
Thread.sleep();线程一段时间内休眠,可能引起并发问题
public class Web12306 implements Runnable{
private int num = 50;
public void run(){
while(true){
if (num<=0) {
try {
Thread.sleep(1000);//会出现并发问题,多个线程获取同一个数据
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
if (num==1) {
System.out.println(Thread.currentThread().getName()+"抢到了");//多线程共享资源冲突问题
}
System.out.println(Thread.currentThread().getName()+"Get"+num--);
}
}
public static void main(String[] args) {
//真实对象
Web12306 web = new Web12306();
//代理
Thread t1 = new Thread(web, "a");
Thread t2 = new Thread(web, "b");
Thread t3 = new Thread(web, "c");
//启动线程
t1.start();
t2.start();
t3.start();
}
}
new Thread.join();加入另一线程
/**
* join :合并线程
* @author Administrator
*
*/
public class JoinTest extends Thread {
public static void main(String[] args) throws InterruptedException {
JoinTest join = new JoinTest();
Thread t =new Thread(join);//新生
t.start();//就绪
//cpu分配时间片 启动
for (int i = 0; i < 100; i++) {
if (i==50) {
t.join();//阻塞,加入另一线程
}
System.out.println("main。。。");
}
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("join。。。");
}
}
}
Thread.yield();暂停当前线程
/**
* yield :暂停线程
* @author Administrator
*
*/
public class YieldTest extends Thread {
public static void main(String[] args) throws InterruptedException {
YieldTest join = new YieldTest();
Thread t =new Thread(join);//新生
t.start();//就绪
//cpu分配时间片 启动
for (int i = 0; i < 20; i++) {
if (i%5==0) {
Thread.yield();//阻塞,暂停当前线程
}
System.out.println("main。。。"+i);
}
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("Yield。。。"+i);
}
}
}
线程停止 stop 使用标识符 ; 调用线程stop();方法
/**
* 使用标识符结束线程
* @author Administrator
*
*/
public class StopThread {
public static void main(String[] args) throws InterruptedException {
Study s = new Study();
// Thread porxy = new Thread(s);
// porxy.start();
new Thread(s).start();
Thread.sleep(1000);
s.setFlag(false);
}
}
class Study implements Runnable{
private boolean flag = true;
@Override
public void run() {
while(flag){
System.out.println("线程运行");
}
System.out.println("使用标识符结束线程");
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}