赞
踩
Java中创建线程主要有三种⽅式,分别为继承Thread类、实现Runnable接⼜、实现Callable接口。
public class ThreadTest {
public static class MyThread extends Thread {
@Override
public void run () {
System.out.println( "This is child thread" ) ;
}
}
public static void main ( String [] args) {
MyThread thread = new MyThread ();
thread.start();
}
}
run()
方法,然后创建 Thread 对象,将 Runnable 对象作为参数传递给 Thread 对象,调用 start()
方法启动线程。class RunnableTask implements Runnable {
public void run() {
System.out.println("上岸、上岸!");
}
public static void main(String[] args) {
RunnableTask task = new RunnableTask();
Thread thread = new Thread(task);
thread.start();
}
}
call()
方法start()
方法启动线程。class CallableTask implements Callable<String> {
public String call() {
return "上岸、上岸了!";
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
CallableTask task = new CallableTask();
FutureTask<String> futureTask = new FutureTask<>(task);
Thread thread = new Thread(futureTask);
thread.start();
System.out.println(futureTask.get());
}
}
状态 | 说明 |
---|---|
NEW | 初始状态:线程被创建,但还没有调用 start()方法 |
RUNNABLE | 运行状态:Java 线程将操作系统中的就绪和运行两种状态笼统的称作“运行” |
BLOCKED | 阻塞状态:表示线程阻塞于锁 |
WAITING | 等待状态:表示线程进入等待状态,进入该状态表示当前线程需要等待其他线程做出一些特定动作(通知或中断) |
TIME_WAITING | 超时等待状态:该状态不同于 WAITIND,它是可以在指定的时间自行返回的 |
TERMINATED | 终止状态:表示当前线程已经执行完毕 |
sleep()
和 wait()
是 Java 中用于暂停当前线程的两个重要方法sleep()
方法在指定的时间过后,线程会自动唤醒继续执行。wait()
方法需要依靠 notify()
、notifyAll()
方法或者 wait()
方法中指定的等待时间到期来唤醒线程。一个线程调用共享对象的 wait()
方法时,它会进入该对象的等待池,并释放已经持有的该对象的锁,进入等待状态,直到其他线程调用相同对象的 notify()
或 notifyAll()
方法。
一个线程调用共享对象的 notify()
方法时,它会唤醒在该对象等待池中等待的一个线程,使其进入锁池,等待获取锁。
管道输入/输出流和普通的文件输入/输出流或者网络输入/输出流不同,它主要用于线程之间的数据传输,而传输的媒介为内存。
[管道输入/输出流]主要包括了如下 4 种具体实现:PipedOutputStream、PipedInputStream、 PipedReader 和 PipedWriter,前两种面向字节,而后两种面向字符。
如果一个线程 A 执行了 thread.join()
语句,其含义是:当前线程 A 等待 thread 线程终止之后才从 thread.join()
返回。
ThreadLocal是 Java 中提供的一种用于实现线程局部变量的工具。它允许每个线程都拥有自己的独立副本,从而实现线程隔离。ThreadLocal 可以用于解决多线程中共享对象的线程安全问题。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。