sleep()、join()
import java.lang.Thread;
import java.io.IOException;
public class Test3
{
private int i = 10;
private Object object = new Object();
public static void main(String[] args) throws IOException{
Test3 t = new Test3();
MyThread thread1 = t.new MyThread();
MyThread thread2 = t.new MyThread();
thread1.start();
thread2.start();
try {
System.out.println("线程"+Thread.currentThread().getName()+"等待");
thread2.join();
System.out.println("线程"+Thread.currentThread().getName()+"继续执行");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
class MyThread extends Thread
{
@Override
public void run(){
i++;
System.out.println("i:"+i);
try{
System.out.println("线程"+Thread.currentThread().getName()+"进入睡眠状态");
Thread.currentThread().sleep(10000);
}catch(InterruptedException e){
System.out.println("进程睡眠失败");
}
System.out.println("线程"+Thread.currentThread().getName()+"睡眠结束");
i++;
System.out.println("i:"+i);
}
}
}
interrupt()
import java.lang.Thread;
import java.io.IOException;
public class Test4
{
private int i = 0;
public static void main(String[] args) throws IOException
{
Test4 t = new Test4();
MyThread thread0 = t.new MyThread();
MyThread thread1 = t.new MyThread();
thread0.start();
thread1.start();
thread1.interrupt();
}
class MyThread extends Thread
{
@Override
public void run(){
i++;
System.out.println("i:"+i);
try{
System.out.println("线程"+Thread.currentThread().getName()+"进入睡眠");
Thread.currentThread().sleep(10000);
System.out.println("线程"+Thread.currentThread().getName()+"睡眠完毕");
}catch(InterruptedException e){
System.out.println("线程"+Thread.currentThread().getName()+"中断异常");
}
System.out.println("run方法执行完毕");
i++;
System.out.println("i:"+i);
}
}
}