线程start()后可能不会立刻开始执行,只是设置为runable状态,具体取决于cpu的调度。
简写
new Thread(new Runnable() {
@Override
public void run() {
while(true)
System.out.println("running");
}
}).start();
有三种方式:
1. 创建一个Thread的子类。
public class MyThread extends Thread {
private static int a = 0;
@Override
public void run() {
for(;;){
if(a >= 100){
return;
}
//Thread.yield();
System.out.println(Thread.currentThread().getName()+ " "+a);
a++;
}
}
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
MyThread myThread1 = new MyThread();
MyThread myThread2 = new MyThread();
myThread.start();
myThread1.start();
myThread2.start();
}
2. 创建一个实现Runnable接口的子类。
public class MyRunnable implements Runnable {
private int a = 0;
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
// try {
// Thread.sleep(3000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//创建线程执行目标类对象
MyRunnable myRunnable = new MyRunnable();
//创建线程对象,传入线程执行目标类对象
Thread t1 = new Thread(myRunnable,"花花");
Thread t2 = new Thread(myRunnable,"红红");
Thread t3 = new Thread(myRunnable,"兰兰");
//启动线程
t1.start();
t2.start();
t3.start();
}
3. 创建一个实现Callable接口的子类。
FutureTask futureTask=new FutureTask(new Callable() {
@Override
public String call() throws Exception {
Thread.sleep(3000);
System.out.println("calld方法执行了");
return "call方法返回值";
}
});
futureTask.run();
System.out.println("获取返回值: " + futureTask.get());
FutureTask futureTask1=new FutureTask(new Callable() {
@Override
public String call() throws Exception {
Thread.sleep(3000);
System.out.println("calld方法执行了1");
return "call方法返回值1";
}
});
futureTask1.run();
System.out.println("获取返回值1: " + futureTask1.get());
第二种较为常用。
评论区