Joa*_*uer 33
有一种方法可以在Java中创建一个新线程,即实例化java.lang.Thread(实际运行该线程,您还需要调用start()).
在Java代码中创建线程的所有其他东西都会回到封面后面的这一方面(例如,ThreadFactory实现将Thread在某个时刻实例化对象,......).
有两种不同的方法可以指定在该Thread中运行的代码:
java.lang.Runnable,并通过它实现的类的实例的Thread构造.Thread自身并覆盖其run()方法.第一种方法(实现Runnable)通常被认为是更正确的方法,因为您通常不会创建新的"类型"的Thread,而只是想Runnable在专用线程中运行一些代码(即a ).
ank*_*249 21
线程可以主要以3种不同的方式创建
class SampleThread extends Thread {
//method where the thread execution will start
public void run(){
//logic to execute in a thread
}
//let’s see how to start the threads
public static void main(String[] args){
Thread t1 = new SampleThread();
Thread t2 = new SampleThread();
t1.start(); //start the first thread. This calls the run() method.
t2.start(); //this starts the 2nd thread. This calls the run() method.
}
}
Run Code Online (Sandbox Code Playgroud)
class A implements Runnable{
@Override
public void run() {
// implement run method here
}
public static void main() {
final A obj = new A();
Thread t1 = new Thread(new A());
t1.start();
}
}
Run Code Online (Sandbox Code Playgroud)
class Counter implements Callable {
private static final int THREAD_POOL_SIZE = 2;
// method where the thread execution takes place
public String call() {
return Thread.currentThread().getName() + " executing ...";
}
public static void main(String[] args) throws InterruptedException,
ExecutionException {
// create a pool of 2 threads
ExecutorService executor = Executors
.newFixedThreadPool(THREAD_POOL_SIZE);
Future future1 = executor.submit(new Counter());
Future future2 = executor.submit(new Counter());
System.out.println(Thread.currentThread().getName() + " executing ...");
//asynchronously get from the worker threads
System.out.println(future1.get());
System.out.println(future2.get());
}
}
Run Code Online (Sandbox Code Playgroud)
使用Executor框架的Callable接口进行线程池化.
Runnable或Callable接口比扩展Thread类更受欢迎
| 归档时间: |
|
| 查看次数: |
56918 次 |
| 最近记录: |