线程状态
NEW:创建线程,未start
RUNNABLE:等待调度或者已经在执行
BLOCKED:等锁
WAITING:等待其他线程的动作,如wait或者interrupt
TIMED_WAITING:可以在指定时间内返回
TERMINATED:线程执行完毕
实现线程的4种方式
实现Runnable接口
public class MyThreadImpRunnable implements Runnable {
@Override
public void run() {
while (true) {
System.out.println("hello damon!");
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Thread t = new Thread(new MyThreadImpRunnable());
t.start();
}
}
继承Thread类
public class MyThreadExendThread extends Thread {
@Override
public void run() {
while (true) {
System.out.println("hello damon!");
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyThreadExendThread mtet = new MyThreadExendThread();
mtet.start();
}
}
实现Callable接口
package com.chengjie.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class MyThreadImplCallable implements Callable<String> {
@Override
public String call() throws Exception {
String str = "hello damon";
return str;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyThreadImplCallable mt = new MyThreadImplCallable();
FutureTask<String> ft = new FutureTask<String>(mt);
new Thread(ft).start();
System.out.println(ft.get());
}
}
通过线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyThreadProducedByThreadPoolExecutor implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "线程被调用了");
}
public static void main(String[] args) {
ExecutorService es = Executors.newFixedThreadPool(10);
// ExecutorService es = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
es.execute(new MyThreadProducedByThreadPoolExecutor());
System.out.println("***************" + i + "***************");
}
es.shutdown();
}
}
线程常用方法
静态方法
yield():建议让出执行权,实际不一定调度不到此线程
currentThread():获取当前线程
sleep():休眠,不让出锁
interrupted():get and set
package javase;
public class TestThread extends Thread{
@Override
public void run() {
// yield();
if (isInterrupted()) {
System.out.println("this thread is interrupt");
System.out.println("clear the tag " + interrupted());
}
while (true) {
}
}
public static void main(String[] args) {
Thread t = new TestThread();
t.start();
t.interrupt();
System.out.println("+++++++++++++++++++++++++++++");
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("=============================");
t.interrupt();
if (t.isInterrupted()) {
System.out.println("t is interrupted");
}
System.out.println(t.isInterrupted());
}
}
非静态方法
join():当前线程等待调用join方法的线程执行完再执行,可加参数表示等待多久
package javase;
public class TestJoinLong extends Thread{
@Override
public void run() {
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " end!");
}
public static void main(String[] args) {
Thread t = new TestJoinLong();
t.start();
try {
t.join(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " end!");
}
}
interrupt():打断调用线程,实际设置一个标记
isInterrupted():判断调用线程是否被打断
isAlive():判断线程是否还存活
setName():设置线程名
getName():获取线程名
setPriority():设置优先级
getPriority():获取优先级
getThreadGroup():获取线程组
activeCount():获取当前线程所在线程组的存活线程
setDaemon():设置线程为守护线程,需要在start()前调用
isDaemon():判断当前线程是否为守护线程
import static java.lang.Thread.sleep;
class MyClass implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("In Treads [" + Thread.currentThread().getName() + "]");
System.out.println(Thread.currentThread().getName() + "[" + i + "]");
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class TestThread {
public static void main(String[] args) {
Thread t1 = new Thread(new MyClass(), "MyClass1");
Thread t2 = new Thread(new MyClass(), "MyClass2");
t1.setDaemon(true);
t2.setDaemon(true);
t1.start();
t2.start();
System.out.println(Thread.currentThread().getName() + " end!");
}
}
getId():获取线程编号
getState():获取线程状态,如在运行中、时间片等待中
Object中相关方法
wait():线程进入阻塞状态,等待唤醒和锁
notify():唤醒等待的线程
- 必须有锁
- wait()会释放锁,sleep不会
-
时间等待、阻塞
示例:两个线程分别打印奇数和偶数,输出123456...
package javase;
class ThreadA extends Thread {
private Object o;
public ThreadA(Object o) {
super();
this.o = o;
}
@Override
public void run() {
synchronized (o) {
for (int i = 100; i < 110; i += 2) {
System.out.println("1");
o.notify();
System.out.println("2");
System.out.println(i);
System.out.println("3");
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("4");
}
}
}
}
class ThreadB extends Thread {
private Object o;
public ThreadB(Object o) {
super();
this.o = o;
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o) {
for (int i = 101; i < 110; i += 2) {
System.out.println("5");
o.notify();
System.out.println("6");
System.out.println(i);
System.out.println("7");
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("8");
}
}
}
}
public class TestPrint {
public static void main(String[] args) {
Object o = new Object();
ThreadA a = new ThreadA(o);
ThreadB b = new ThreadB(o);
a.start();
b.start();
}
}
- 只有走出同步区才会释放锁
public class TestWaitNotify {
public static Object o = new Object();
static class ThreadA extends Thread {
@Override
public void run() {
synchronized (o) {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
static class ThreadB extends Thread {
@Override
public void run() {
synchronized (o) {
for (int i = 101; i < 200; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
Thread t1 = new ThreadA();
Thread t2 = new ThreadB();
t1.start();
t2.start();
}
}