一、线程的创建:
- 用Java创建一个线程是这样的:
Thread thread = new Thread();
要启动Java线程,您将调用其start()方法,如下所示:
thread.start();
此示例未指定要执行的线程的任何代码。线程启动后会立即再次停止。
二、指定线程执行代码:
1、创建Thread子类,覆盖run()方法;
package com.thread;
public class ThreadTest extends Thread{
public static void main(String[] args) {
ThreadTest test = new ThreadTest();
test.start();
}
@Override
public void run() {
System.out.println("(o.o)");
}
}
Thread thread = new Thread(){
@Override
public void run() {
System.out.println("(^.^)");
}
};
thread.start();
start()
一旦线程启动 ,调用将立即返回。
调用start()方法和run()方法区别:
start():线程启动,创建了一个新的线程执行;
run():是方法的调用,仍在主线程中执行。
2、实现Runnable接口
package com.thread;
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Test Runnable");
}
}
package com.thread;
public class TestRunnable {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread t = new Thread(runnable);
t.start();
}
}
3.Callable接口
package com.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class CallableTest implements Callable<String>{
@Override
public String call() throws Exception {
System.out.println("Test");
return "(* ̄︶ ̄)";
}
public static void main(String[] args) throws Exception {
CallableTest c = new CallableTest();
FutureTask<String> ft = new FutureTask<>(c);
Thread t = new Thread(ft);
t.start();
String call = c.call();
System.out.println(call);
}
}
三、线程的生命周期
四、常用方法介绍:
- isAlive() 判断线程是否终止
boolean alive = tt.isAlive();
2.Thread.sleep() 让线程睡眠指定的时间,毫秒为单位。
sleep方法导致了在指定的时间内,程序暂停执行,让出CPU给其他线程,但是他的监控状态依然保持着,挡道了指定的时间到了又会自动恢复运行状态。
调用sleep(),线程不会释放对象锁。
Thread.sleep(2000);
3.getName() 获取线程名称
Thread tt = new Thread();
String name = tt.getName();
4.Thread.currentThread() 返回对当前正在执行的线程对象的引用。
Thread currentThread = Thread.currentThread();
5.join() 等待该线程执行结束,再回复当前线程的执行。
public class TestThread extends Thread{
public void run(){
for (int i = 0; i < 4; i++) {
System.out.println(Thread.currentThread().getName()+ "********" + i);
}
}
public static void main(String[] args) {
for (int i = 0; i < 11; i++) {
System.out.println(Thread.currentThread().getName() + "-------" + i);
if (i == 5) {
try {
TestThread t = new TestThread();
t.start();
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
运行结果:
6.yield 暂停当前正在执行的线程对象,并执行其他线程。高风亮节,暂停自己,执行别人,自己在就绪队列排队等待。
参考:
[1]:http://tutorials.jenkov.com/java-concurrency/creating-and-starting-threads.html