Java学习笔记(线程2:线程阻塞_join_yield_sle
线程阻塞
1、join:合并线程
package com.bjsxt.thread.status;
/**
* join:合并线程
* @author yingjun
*
*/
public class JoinDemo01 extends Thread{
public static void main(String[] args) throws InterruptedException {
JoinDemo01 demo = new JoinDemo01();
Thread t = new Thread(demo); //新生
t.start(); //就绪
//cpu调度运行
for(int i=0;i<100;i++) {
if(50==i) {
t.join();
}
System.out.println("main-->..."+i);
}
}
@Override
public void run() {
for(int i=0;i<1000;i++) {
System.out.println("join-->..."+i);
}
}
}
2、yield:暂停自己的线程,静态方法
package com.bjsxt.thread.status;
public class YieldDemo01 extends Thread{
public static void main(String[] args) {
YieldDemo01 demo = new YieldDemo01();
Thread t = new Thread(demo); //新生
t.start(); //就绪
//cpu调度运行
for(int i=0;i<100;i++) {
if(i%20==0) {
//暂停本线程main
Thread.yield();
}
System.out.println("main-->..."+i);
}
}
public void run() {
for(int i=0;i<1000;i++) {
System.out.println("yield-->..."+i);
}
}
}
3、sleep,休眠不释放锁
1)、与时间相关,倒计时
package com.bjsxt.thread.status;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 倒计时
* 1、倒数10个数,1秒内打印一个
* 2、倒计时
* @author yingjun
*
*/
public class SleepDemo01 {
public static void main(String[] args) throws InterruptedException {
Date endTime = new Date(System.currentTimeMillis()+10*1000);
long end = endTime.getTime();
while(true) {
//输出
System.out.println(new SimpleDateFormat("mm:ss").format(endTime));
//等待一秒
Thread.sleep(1000);
//构建下一秒时间
endTime = new Date(endTime.getTime()-1000);
//10秒以内 继续 否则 退出
if(end-10000>endTime.getTime()) {
break;
}
}
}
public static void test1() throws InterruptedException {
int num = 10;
while(true) {
System.out.println(num--);
Thread.sleep(1000); //暂停
if(num==0) {
break;
}
}
}
}
2)、模拟网络延时 (这里有个统一资源并发的问题)
package com.bjsxt.thread.status;
/**
* 模拟网络延时
* @author yingjun
*
*/
public class SleepDemo02 {
public static void main(String[] args) {
//真实角色
Web12306 web = new Web12306();
//代理
Thread t1 = new Thread(web,"路人甲");
Thread t2 = new Thread(web,"黄牛乙");
Thread t3 = new Thread(web,"工程师");
//启动线程
t1.start();
t2.start();
t3.start();
}
}
class Web12306 implements Runnable {
private int num = 10;
@Override
public void run() {
while(true) {
if(num<=0) {
break; //跳出循环
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"抢到了"+num--);
}
}
}
当还剩一张票时,可能会引起抢到0张票和-1张票的情况