发表于: java/j2ee | 作者: | 日期: 2008/12/20 03:12

线程的基本概念

当程序启动时,就自动产生了一个线程。主函数main就是在这个线程上运行的。当不产生新的线程时,程序就是单线程的。

创建多线程有两种方法:继承Thread类或者继承自Runnable接口。

用Thread类实现多线程


package com.darkmi.sandbox;

public class ThreadDemo {

public static void main(String[] args) {
new TestThread().start();
System.out.println(“here”);
}
}

class TestThread extends Thread{
public void run(){
while(true){
System.out.println(Thread.currentThread().getName() + ” is running ! “);
}
}
}

输出:

Thread-0 is running !
Thread-0 is running !
Thread-0 is running !
Thread-0 is running !
….

说明:
(1)
要将一段代码放在一个新的线程上运行,该代码应该在一个类的run函数中,并且run函数所在的类是Thread类的子类。
(2)
启动一个新的线程,不是直接调用Thread类的子类对象的run方法,而是调用Thread子类对象的start()(由Thread类的继承的)方法。Thread类对象的start方法将产生一个新的线程,并在该线程上运行该Thread子类对象中的run方法。
(3)
由于线程的代码在run方法中,那么该方法执行完毕之后,线程也就相应的结束了,因此可以通过控制run方法中循环条件来控制线程的终止。

用Runnable接口实现多线程


package com.darkmi.sandbox;

public class ThreadDemo {

public static void main(String[] args) {
new TestThread().start();
System.out.println(“here”);
}
}

class TestThread implements Runnable{
public void run(){
while(true){
System.out.println(Thread.currentThread().getName() + ” is running ! “);
}
}
}

输出:

Thread-0 is running !
Thread-0 is running !
Thread-0 is running !
Thread-0 is running !
….

如何启动多个线程


package com.darkmi.sandbox;

public class ThreadDemo {

public static void main(String[] args) {
TestThread t = new TestThread();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}

class TestThread implements Runnable{
private int tickets = 100;
public void run(){
if(tickets > 0){
System.out.println(Thread.currentThread().getName() + ” is saling ticket ” + tickets– );
}
}
}

: https://blog.darkmi.com/2008/12/20/722.html

本文相关评论 - 1条评论都没有呢
Post a comment now » 本文目前不可评论

No comments yet.

Sorry, the comment form is closed at this time.