标签:
两种方法创建线程 1、 extends Thread这个类. 2、 implements Runnable这个接口.
set Daemon(); 创建一个后台进程; tt.join("a") 意思为将某线程加入tt (a)ms后, 再释放某线程;
使用 Runnable优点:
优化java语言的单继承性;
适合多个线程使用同一资源情况;
火车售票窗口共100张票, 用线程模拟一下;
用法:
class ThreadDemo
{
public static void main(String[] args)
{
TestThread tt=new TestThread(); //启用多个线程, 多线程共享资源;
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
}
}
class TestThread implements Runnable
{
int tickets=100;
public void run()
{
while(true)
{
//System.out.println("run() :"+Thread.currentThread().getName());
while(tickets-- >0)
System.out.println(Thread.currentThread().getName()+" is sailing ticket " + tickets--);
}
}
}
class ThreadDemo
{
public static void main(String[] args)
{
new TestThread().start(); //启用多个线程, 每个线程资源独立;
new TestThread().start();
new TestThread().start();
new TestThread().start();
/*TestThread tt=new TestThread();
tt.start();
tt.start();
tt.start();
tt.start();*/
}
}
class TestThread extends Thread
{
int tickets=100;
public void run()
{
while(true)
{
//System.out.println("run() :"+Thread.currentThread().getName());
while(tickets-- >0)
System.out.println(Thread.currentThread().getName()+" is sailing ticket " + tickets--);
}
}
}
标签:
原文地址:http://www.cnblogs.com/ceal/p/5303733.html