zoukankan      html  css  js  c++  java
  • java -- 线程

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

     

    多线程的实际应用举例:

      网络聊天程序信息的收发。

          www服务器为每一个来访者都建立专线服务。

      表复制的中途取消。

    知识点 http://blog.csdn.net/csh624366188/article/details/7318245

    同步代码块和同步函数不一定同步;

    线程死锁:

      在同步代码块或同步函数中调用的wait(); notify(); notifyall();的调用对象不是 用作标记的对象;

    线程间的通信:

      wait(): 告诉当前线程放弃监视器synthronized(){}并进入睡眠状态直到其他线程 进入同一监视器并调用notify(); 为止。

      notify(): 唤醒同一对象监视器中调用wait();的第一个线程, 用于类似饭馆有一个空位后通知所有等候就餐的顾客的第一位可以入座的情况。

          notifyAll(); 唤醒同一对象监视器中调用wait();的所有线程, 且具有最高优先级的线程首先被唤醒并执行。 用于类似某个不定期的培训班终于招生满额后, 通知所有学员都来上课的情况.

    //线程间通信, 生产者产生一个, 消费者消耗一个, Error: 生产一个被消费多次。 同一个被生产多次 以及线程的安全(死锁)。
    class Producer implements Runnable
    {
        Q q;
        public Producer(Q q)
        {
            this.q=q;
        }
        public void run() 
        {
            
            int i=0;
            while(true)
            {
                /*synchronized(q)
                {
                    if(q.bFull)
                        try{q.wait();} catch(Exception e) {} 
                    if(i==0)
                    {
                        q.name="zhangsan";
                        try{Thread.sleep(10);} catch(Exception e) {}
                        q.sex="male";
                    }
                    else
                    {
                        q.name="lisi";
                        q.sex="female";
                    }
                    q.bFull=true;
                    q.notify();
                }*/
                if(i==0)
                    q.put("zhangsan" ,"male");
                else
                    q.put("lisi", "female");
                i=(i+1)%2;
            }
        }
    } 
    
    class Consumer implements Runnable
    {
        Q q;
        public Consumer(Q q)
        {
            this.q=q;
        }
        public void run() 
        {
            while(true)
            {
                /*synchronized(q)
             {
                    if(!q.bFull)
                        try{q.wait();} catch(Exception e) {}
                    System.out.print(q.name);
                    System.out.println(" is " + q.sex);
                    q.bFull=false;
                    q.notify();
                }*/
                q.get();
            }
        }
    }
    
    class Q
    {
        private String name="unknown";
        private String sex="unknown";
        private boolean bFull=false;
        String str=new String();
        //synchronized(str)
        //{
        public synchronized void put(String name, String sex)
        {
            if(bFull)
                try{wait();} catch(Exception e) {};
            this.name=name;
            try{Thread.sleep(1);} catch(Exception e){}
            this.sex=sex;
            bFull=true;
            notify();
        }
        public synchronized  void get()
        {
            if(!bFull)
                try{wait();} catch(Exception e){}
            System.out.print(name);
            System.out.println(" is "+sex);
            bFull=false;
            //try{wait();} catch(Exception e){}
            notify();
        }
        //}
    }
    class ThreadCommunation
    {
        public static void main(String[] args)
        {
            Q q=new Q();
            new Thread(new Producer (q)).start();
            new Thread(new Consumer (q)).start();
        }
    }

    线程生命周期:

    class ThreadTest1
    {
        public static void main(String[] args)
        {
            ThreadTest t=new ThreadTest();
            new Thread(t).start();
            for(int i=1; i<=100; i++)
            {
                if(i==50)
                    t.stopMe();
                System.out.println("main() is running!");
            }
        }
    }
    class ThreadTest implements Runnable
    {
        private boolean bStop=false;   //程序的封装性 ; 
        public void stopMe()           
        {
            bStop=true;
        }
        int times=0;
        public void run()
        {
          while(!bStop)             //通过一个变量控制程序生命周期 ;
            {
                System.out.println(Thread.currentThread().getName()+" is running."+ times++);
            }
        }
    }

      

  • 相关阅读:
    [日常摸鱼]最小费用最大流
    [日常摸鱼]loj6000「网络流 24 题」搭配飞行员
    [日常摸鱼]最大流
    [日常摸鱼]poj1741Tree-点分治
    [游记]FCS&FJOI2018滚粗记
    TOJ-1469-Wooden Sticks(贪心)
    TOJ-1188-田忌赛马(贪心)
    TOJ3988-Password(已知二叉树前中序求后序)
    枚举HDU-1172猜数字
    模拟题 HDU3052 VIM
  • 原文地址:https://www.cnblogs.com/ceal/p/5303733.html
Copyright © 2011-2022 走看看