线程创建
———————————————————————————————————————————————————————————————————————
———————————————————————————————————————————————————————————————————————
第二种写法:
将实现runnable接口的对象当作Thread线程对象的参数 ,通过Thread线程对象.start()来开启线程
public class ThreadTest implements Runnable{
@Override
public void run() {
for (int i = 0; i < 7; i++) {
System.out.println("run方法");
}
}
public static void main(String[] args) {
ThreadTest threadtest = new ThreadTest();
//创建runnable接口的实现类的对象
Thread thread = new Thread(threadtest);
//创建线程对象,通过线程对象来开启我们的线程,通过代理的方式
thread.start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
//或者
new Thread(threadtest).start();
for (int i = 0; i < 700; i++) {
System.out.println("main");
}
}
}
线程停止
不推荐JDK提供的stop() destory()方法
建议使用一个标志位来控制停止
public class TestStop implements Runnable{
//1.设置一个标志位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while(flag){
System.out.println("run..." + i++);
}
}
//2. 设置一个停止的方法转换标志位
public void stop(){
this.flag = false;
}
public static void main(String[] args) {
TestStop testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main" + i);
if(i == 900){
testStop.stop();
System.out.println("线程该停止了");
}
//调用stop方法切换标志位让线程停止
}
}
}
线程休眠
线程礼让 yield
class MyYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "线程start");
Thread.yield();
System.out.println(Thread.currentThread().getName() + "线程end");
}
}
public class TestYield{
public static void main(String[] args) {
MyYield testYield = new MyYield();
new Thread(testYield,"a").start();
new Thread(testYield,"b").start();
}
}
加了Thread.yield();之后会提高礼让的概率,但也有可能礼让不成功
run()方法中的执行流程是:先执行第一个sout,然后礼让,之后再执行第二个sout。
线程强制执行Join
Join合并线程,待此线程执行完毕后,再执行其他线程,其他线程阻塞
可以想象为插队
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("插队线程来了" + i);
}
}
//类似插队
public static void main(String[] args) throws InterruptedException {
TestJoin testJoin = new TestJoin();
//testJoin为实现了Runnable接口的对象
Thread thread = new Thread(testJoin);
//将testJoin作为Thread线程对象的参数,然后调用start方法来开启线程
thread.start();
for (int i = 0; i < 500; i++) {
if(i == 200) {
thread.join();
}
System.out.println("main" + i);
}
}
}
这里有两个线程,一个主线程,一个线程,执行效果是主线程for执行到200次之后,开始执行插队线程,在插队线程执行完毕后,才继续执行主线程到结束。