}
//下面这段代码会随情况不同而不同,有时候可能输出false,有时候可能输出true
System.out.println("at the end of main() , t.isAlive() = "+t.isAlive());
}
}
可以发现通过继承Thread类只能创建一个资源对象,
下面是采用实现Runnable接口实现线程
程序清单:ThreadDemo5.java
public class ThreadDemo5
{
public static void main(String [] args)
{
ThreadTest t=new ThreadTest();
//虽然启动了四个线程,但是起到了同步的作用
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}
class ThreadTest implements Runnable //这里实现了Runnable接口
{
private int tickets=100;
public void run()
{
while(true)
{
if(tickets>0)
System.out.println(Thread.currentThread().getName() +
" is saling ticket " + tickets--);
}
}
}
public class DaemonThread
{
public static void main(String args[])
{
ThreadTest t = new ThreadTest() ;
Thread tt = new Thread(t) ;
/*
对
Java程序来说,只要还有一个前台线程在运行,这个进程就不会结束,如果一个进程中只有后台线程运行,这个进程就会结束,如果某个线程对象在启动(调用start方法)之前调用了setDaemon(true)方法,这个线程就变成了后台线程。
*/
tt.setDaemon(true) ; //设置后台运行
tt.start();
}
}
class ThreadTest implements Runnable
{
public void run()
{
while(true)
{
// Thread.currentThread().getName(),得到当前运行的线程的名称
System.out.println(Thread.currentThread().getName()+”is running.”);
}
}
}
使用Thread.sleep()
此方法用于将线程短暂休眠
TwoThreadSleep.java
public class TwoThreadSleep extends Thread {
public void run() {
loop();
共21页 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21