一个线程并不激动人心,多个线程才有实际意义。怎样创建更多的线程呢?我们需要创建线程类的另一个实例。当我们构造了线程类的一个新的实例,我们必须告诉它在新的线程里应执行哪一段程序。你可以在任意实现了启动接口的对象上启动一个线程。启动接口是一个抽象接口,来表示本对象有一个函数想异步执行。要实现启动接口,一个类只需要有一个叫run的函数。下面是创建一个新线程的例子:
Filename:twothread.java
public class twothread implements Runnable {
public twothread() {
Thread t1 =Thread.currentThread();
t1.setName("The first main thread");
System.out.println("The running thread:" + t1);
Thread t2 = new Thread(this,"the second thread"); //创建了一个Thread对象
System.out.println("creat another thread");
t2.start();
try {
System.out.println("first thread will sleep");
Thread.sleep(3000);
}
catch (InterruptedException e) {
System.out.println("first thread has wrong");
}
System.out.println("first thread exit");
}
public void run() {
try {
for (int i=0;i<5;i++) {
System.out.println("Sleep time for thread 2:"+i);
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
System.out.println("thread has wrong");
}
System.out.println("second thread exit");
}
public static void main(String[] args) {
new twothread();
}
}
执行结果:java twothread
The running thread:Thread[The first main thread,5,main]
creat another thread first thread will sleep
Sleep time for thread 2:0
Sleep time for thread 2:1
Sleep time for thread 2:2
first thread exit Sleep time for thread 2:3
Sleep time for thread 2:4
second thread exit
main线程用new Thread(this, "the second thread")创建了一个Thread对象,通过传递第一个参 数来标明新线程来调用this对象的run函数。 然后我们调用start函数,它将使线程从run函数开始执行。
7.1.3 同步 考试站网校
因为多线程给提供了程序的异步执行的功能,所以在必要时必须还提出一种同步机制。 例如,想两个线程通讯并共享一个复杂的数据结构,你需要一种机制让他们相互牵制并正确执 行。 为这个目的,Java用一种叫监视器(monitor)的机制实现了进程间的异步执行。可以将监视器看作是一个很小的盒子,它只能容纳一个线程。一个线程进入一个监视器,所有其他 线程必须等到第一个线程退出监视器后才能进入。这个监视器可以设计成保护共享的数据不被多个线程同时操作。
大多数多线程系统将这个监视器设计成对象,Java提出了一种更清晰的解决方案。没有Monitor类;每个对象通过将他们的成员函数定义成synchronized来定义自己的显式监视器,一个线程执行在一个synchronized函数里,其他任何线程都不能 调用同一个对象的synchronized函数。
7.1.4 消息
当程序被分成几个逻辑线程,你必须清晰的知道这些线程之间应怎样相互通讯。Java 提出了wait和notify等功能来使线程之间相互交谈。一个线程可以进入 某一个对象的synchronized 函数进入等待状态,直到其他线程显式地将它唤醒。可以有多个线程进入同一个函数并等待同一个唤醒消息。