1 两种实现方式:
image.png
2 创建多个线程如何正确执行?
2.1错误示例:多个线程都执行一遍同一个任务
package io.github.lxqjss;
public class ThreadTest extends Thread{
private int coutNum = 5;
@Override
public void run() {
while (coutNum>0){
coutNum--;
System.out.println("还剩下票数:"+coutNum);
}
}
public static void main(String []args){
ThreadTest threadTest1 = new ThreadTest();
ThreadTest threadTest2 = new ThreadTest();
ThreadTest threadTest3 = new ThreadTest();
threadTest1.start();
threadTest2.start();
threadTest3.start();
System.out.println("ok");
}
}
执行截图:
image.png
2.2 让多个线程交替执行某个任务,达到最大化利用cpu才是目的
package io.github.lxqjss;
public class RunnableTest implements Runnable{
private int coutNum = 5;
@Override
public void run() {
while (coutNum>0){
coutNum--;
System.out.println(Thread.currentThread().getName()+"还剩下票数:"+coutNum);
}
}
public static void main(String []args){
RunnableTest runnableTest = new RunnableTest();
Thread threadTest1 = new Thread(runnableTest,"1号");
Thread threadTest2 = new Thread(runnableTest,"2号");
Thread threadTest3 = new Thread(runnableTest,"3号");
threadTest1.start();
threadTest2.start();
threadTest3.start();
// System.out.println("ok");
}
}
image.png
网友评论