首页 > 编程语言 > 详细

java -- 线程

时间:2016-03-21 21:34:26      阅读:187      评论:0      收藏:0      [点我收藏+]

两种方法创建线程 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--);
        }
    }
}

  

java -- 线程

原文:http://www.cnblogs.com/ceal/p/5303733.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!