
第一种方法:编写一个类,继承Thread,重写run方法
package com.company;
public class ThreadTest02 {
public static void main(String[] args) {
//main方法,主站中运行
//新建一个分支线程对象
Mythread m = new Mythread();
//启动线程
m.start();//start 作用:在JVM 开票一个新的栈空间,这段代码任务完成之后,
//瞬间就结束了。
// 启动成功的线程会自动调用run方法
//这里的代码还是运行在线程中
for (int i = 0; i < 100000000; i++) {
System.out.println("主线程" + i);
}
}
}
class Mythread extends Thread {
@Override
public void run() {
//编写程序,这个程序运行在分支站中
for (int i = 0; i < 10000000; i++) {
System.out.println(i);
}
}
}
编写一个类,实现Runnable接口(建议使用)
package com.company;
public class ThreadTest03 {
public static void main(String[] args) {
//编写一个类,实现Runnable接口
//合并在一起
Thread t = new Thread(new my());
//启动线程
t.start();
for (int i = 0; i < 100; i++) {
System.out.println("主线程" + i);
}
}
}
//这并不是一个线程类,只是一个可运行的类,他还不是一个线程
class my implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("分支线程" + i);
}
}
}
获取线程
package com.company;
public class ThreadTest05 {
public static void main(String[] args) {
Thread c = Thread.currentThread();
System.out.println(c.getName());
//创建线程对象
Mythread2 t = new Mythread2();
//设置线程的名字
t.setName("tttt");
//获取线程的名字
String tname = t.getName();
System.out.println(tname);
t.start();
}
}
class Mythread2 extends Thread {
public void run() {
for (int i = 0; i <= 10; i++) {
Thread d = Thread.currentThread();
System.out.println(d.getName() + " " + i);
}
}
}
终止线程的睡眠
package com.company;
//唤醒一个这个在睡眠的进程
public class ThreadTest08 {
public static void main(String[] args) {
Thread t = new Thread(new My());
t.setName("t");
t.start();
//希望5秒之后醒来
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
t.interrupt();
}
}
class My implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "begin");
//子类不能比父类抛出更多的异常
try {
Thread.sleep(1000 * 60 * 60 * 24);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "over");
}
}
合理的终止一个线程
package com.company;
public class ThreadTest09 {
public static void main(String[] args) throws InterruptedException {
MyRunnable3 r = new MyRunnable3();
Thread t = new Thread(new MyRunnable3());
t.setName("t");
t.start();
//模拟五秒
Thread.sleep(1000 * 5);
//5秒后强行终止t线程
r.run = false;
}
}
class MyRunnable3 implements Runnable {
boolean run = true;
@Override
public void run() {
for (int i = 0; i < 10; i++) {
if (run) {
System.out.println(Thread.currentThread().getName() + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
//终止当前线程
//在这里保存
return;
}
}
}
}