1、实现线程的方法
第一种方式:
继承Thread类,重写run方法,如以下代码所示
package Thread;
public class ThreadDemo{
public static void main(String[] args) {
MyThread mt=new MyThread();//启动线程
mt.start();
for (int i = 0; i < 5; i++) {
System.out.println("主线程--->"+i);
}
}
}
package Thread;
public class MyThread extends Thread{
@Override
public void run(){
for (int i = 0; i <5; i++) {
System.out.println("分支线程--->"+i);
}
}
}
mt.start()方法的作用是开启一个新的栈空间,只要新的栈空间开出来,start()方法就结束了。线程就启动成功了。线程启动成功后用自动调用run()方法
第二种方式:
用类实现Runnable接口,如以下代码所示
package Thread;
public class MyRunnable implements Runnable{
@Override
public void run(){
for (int i = 0; i < 5; i++) {
System.out.println("分支线程--->"+i);
}
}
}
package Thread;
public class RunnableDemo{
public static void main(String[] args) {
MyRunnable mr=new MyRunnable();
Thread t=new Thread(mr);
t.start();
for (int i = 0; i < 5; i++) {
System.out.println("主线程--->"+i);
}
}
}
2、线程中的sleep方法
1.它是静态方法
2.参数是毫秒
3、作用:让当前线程进入休眠,进入“阻塞”状态,放弃占有CPU时间片,让给其他线程使用。
public class ThreadDemo {
public static void main(String[] args) {
//让当前线程进入休眠,睡眠10秒
try {
Thread.sleep(1000*10);
} catch (InterruptedException e) {
e.printStackTrace();
}
//10秒之后执行这里的代码
System.out.println("hello world!");
}
}
3、线程中的interrupt方法
interrupt方法的作用是中止线程的休眠
package Thread;
public class ThreadDemo {
public static void main(String[] args) {
MyRunnable mr=new MyRunnable();
Thread t = new Thread(mr);
t.setName("t");
t.start();
//10秒之后,中断t线程的休眠
try {
Thread.sleep(1000*10);
} catch (InterruptedException e) {
e.printStackTrace();
}
t.interrupt();//终断t线程的睡眠
}
}
package Thread;
public class MyRunable implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "--> start");
try {
Thread.sleep(1000*60*60*24);//睡眠1天
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "--> end"); //一天之后才会执行这里
}
}