public class joinDemo1 extends Thread {
public static void main(String[] args) throws InterruptedException {
joinDemo1 ab =new joinDemo1();
Thread t=new Thread(ab);
t.start();
for(int i=0;i<=100;i++)
{
if(i==50)
t.join();
System.out.println(i);
}
}
@Override
public void run() {
for(int i=0;i<=100;i++)
{
System.out.println(i);
}
}
}
当 t.join(); 这个代表必须等t终止后。main方法的线程才会继续执行, t.yield();代表暂停该线程
下面我们重点讲sleep()方法
package cpm.thread.creater;
public class Sleep {
public static void main(String[] args) {
Web12306 ab= new Web12306();
Thread proxy=new Thread(ab,"甲");
Thread proxy2=new Thread(ab,"乙");
Thread proxy3=new Thread(ab,"丙");
proxy.start();
proxy2.start();
proxy3.start();
}
}
class Web12306 implements Runnable
{
private int num =50;
@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--);
}
}
}
为什么要重点讲,并不是sleep方法有多难,运行这个程序,我们会发现最后运行到了 -1.
这是为什么了,实际上我们运行了3个线程,当最后一步时,甲拿走1,乙拿走0,丙拿走-1,这就是多线程对于资源的抢夺,也是并发产生的原因