java 线程理解
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class homework514 {
//run()在完成时不会返回值,Callable接口的call()会产生返回值
public static class Run_test implements Runnable{//使用Runnable接口的run()方法{多线程合作完成任务}
private static int taskCount = 0;
private int priority;
private final int id = taskCount++;//线程id
public Run_test(int priority){
this.priority = priority;
}
public String dispaly(){//多线程就应该在run里面输出
return "线程id:"+id+"优先级:"+priority;
}
public void run(){
Thread.currentThread().setPriority(priority);//run()中是多个线程需要完成的任务
System.out.println(dispaly());
Thread.yield();//线程调度器
}
}
public static Thread getThreadName(String threadName) {
Thread t = new Thread(threadName);
while(true){
//根据线程名取得线程
if (t.getName().equals(threadName)){
return t;
}
return null;
}
}
static class Runner_extend_test extends Thread{//多线程各自完成任务
private int countDown=5;
private String name;
public Runner_extend_test(String name){
this.name = name;
}//以倒计时为例子
public String dispaly(){//多线程就应该在run里面输出
return name+":"+(countDown>0?countDown:"GO!");
}
public void run() {
while (countDown-- > 0) {
System.out.println(dispaly());
}
}
}
public static void main(String[] args)
{
/*
for(int i=1;i<=5;i++)//未设置优先级
{
Thread t = new Thread(new Run_test());//提交给Thread构造器
t.start();
}
*/
/*
//创建一个线程集
ExecutorService exec = Executors.newFixedThreadPool(5);//预先限制数量
for(int i=1;i<=5;i++){
exec.execute(new Run_test());
}
exec.shutdown();
*/
/*
//序列化线程,每一个线程会在下一个线程运行前结束
ExecutorService exec = Executors.newSingleThreadExecutor();//预先限制数量
for(int i=1;i<=5;i++){
exec.execute(new Run_test());
}
exec.shutdown();
*/
/*
//设置线程优先级
ExecutorService exec = Executors.newCachedThreadPool();
Run_test one = new Run_test(Thread.MAX_PRIORITY);
Run_test two = new Run_test(Thread.MIN_PRIORITY);
Run_test three = new Run_test(Thread.NORM_PRIORITY);
exec.execute(one);//10
exec.execute(two);//1
exec.execute(three);//5
System.out.println(getThreadName("one"));
exec.shutdown();
*/
//启动继承Thread的线程
Runner_extend_test run_1=new Runner_extend_test("线程1");
Runner_extend_test run_2=new Runner_extend_test("线程2");
Runner_extend_test run_3=new Runner_extend_test("线程3");
run_1.start();
run_2.start();
run_3.start();
}
}
一切都在代码中
浙公网安备 33010602011771号