java基礎知識 多線程

package org.base.practise9;java

import org.junit.Test;多線程

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;dom

/**
* Created with IntelliJ IDEA.
* User: cutter.li
* Date: 14-3-11
* Time: 上午9:40
* 多線程基礎知識練習
*/
public class PractiseTest {ide

    //1,線程有四種狀態,新建,運行,中斷,死亡
    //2,引發中斷的緣由:sleep,io阻塞,wait,cpu切換線程的時候線程進入中斷狀態
    //3,一個線程執行完run方法,進入死亡狀態, 該線程不能在調用start方法
    //4,線程死亡了,isAlive方法返回的是false
    //5,創建線程有兩種方法,繼承Thread類或者實現Runable接口
    //6,setPriority();方法來設置優先級,一共有十個優先級別
    //7,爲了防止資源競爭產生的死鎖,主要是在寫數據的時候
    //8,同步方法須要掛起線程,恢復掛起的線程的地方使用wait(),notify(),notifyAll()方法
    //9,不合理
    //10,interrupt()吵醒休眠的線程
    @Test
    public void exercise1() {this

        Thread left = new Hand("左手");
        Thread right = new Hand("右手");spa

        left.start();
        right.start();線程

        for(int i=1;i<=10;i++){
            System.out.println("我是主線程");
        }對象

//         left.setPriority();
//        if(!left.isAlive())
        {
            System.out.println("線程left死亡了嗎?"+left.isAlive());
//            left.start();
        }繼承

    }
    //12,寫一個程序,模擬買票(3人排隊買票,售票員只有3張5塊,電影票5塊一張,張某拿一張20,李某拿一張10,趙某拿一張5塊)
    @Test
    public void exercise11() {接口

      Buyer buyer=new Buyer();
        buyer.getZhang().start();
        buyer.getLi().start();
        buyer.getZhao().start();
    }
    //11,寫一個程序,有兩個線程,一個作垂直上拋運動,另一個作模仿45度的拋體運動
    public static void main(String[] args)
    {
//        MyFrame myFrame=new MyFrame();
//        myFrame.setBounds(10,10,500,500);
//        myFrame.setVisible(true);
//        myFrame.addWindowListener(new WindowAdapter() {
//            @Override
//            public void windowClosing(WindowEvent e) {
//                System.exit(0);
//            }
//        });

//        Thread t=new Thread(new Gxy());
//        t.start();

 

        People people=new People();

        people.getTeacher().start();
        people.getStudent1().setName("李福春");
        people.getStudent1().start();
        people.getStudent2().setName("何麗君");
        people.getStudent2().start();
    }

    @Test
    public void exercise13() {

        People people=new People();

        people.getTeacher().start();
        people.getStudent1().start();
        people.getStudent2().start();

    }

    @Test
    public void exercise14() {

        Worker worker=new Worker();
        worker.getSiji().start();
        worker.getBanyun().start();
        worker.getCangguan().start();
    }

}

 

package org.base.practise9;

/**
* Created with IntelliJ IDEA.
* User: cutter.li
* Date: 14-3-11
* Time: 上午11:25
* To change this template use File | Settings | File Templates.
*/
public class Buyer extends Thread {

    Thread zhang=new Thread(this);
    Thread li=new Thread(this);
    Thread zhao=new Thread(this);

    TicketSeller ticketSeller=new TicketSeller();

    public Thread getZhang() {
        return zhang;
    }

    public Thread getLi() {
        return li;
    }

    public Thread getZhao() {
        return zhao;
    }

    public Buyer()
    {

    }


    @Override
    public void run() {
        if(Thread.currentThread()==zhang){
               ticketSeller.sellTicket(20);
        }else if(Thread.currentThread()==li)
        {
            ticketSeller.sellTicket(10);
        }  else  if(Thread.currentThread()==zhao)
        {
              ticketSeller.sellTicket(5);
        }
    }
}

package org.base.practise9;

/**
* Created with IntelliJ IDEA.
* User: cutter.li
* Date: 14-3-11
* Time: 上午11:43
* To change this template use File | Settings | File Templates.
*/
public class Gxy implements Runnable {

    float n=0,zhen=0,fan=0,li=0;


    @Override
    public void run() {
        while (true){
            n++;
            double  i=Math.random();
            if(i<0.5){
                zhen++;
                System.out.println("正面出現的機率 "+zhen/n);
            } else if(i==0.5)
            {
                li++;
                System.out.println("正立出現的機率 "+li/n);
            } else{
                fan++;
                System.out.println("反面出現的機率 "+fan/n);
            }

            try {
                Thread.currentThread().sleep(1000);
                System.out.println("活動線程數:"+ Thread.activeCount());;
            } catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }

        }
    }
}

package org.base.practise9;

/**
* Created with IntelliJ IDEA.
* User: cutter.li
* Date: 14-3-11
* Time: 上午9:41
* 線程
*/
public class Hand extends Thread {


    private String name;

    public Hand(String name) {
        this.name = name;
    }

    @Override
    public void run() {

        print();

    }

    private synchronized void print() {
        for (int i = 1; i <= 10; i++) {
            System.out.println("我是" + name + "線程");
        }


    }
}

package org.base.practise9;

import java.awt.*;

/**
* Created with IntelliJ IDEA.
* User: cutter.li
* Date: 14-3-11
* Time: 上午10:30
* 油畫對象
*/
public class MyCanvas extends Canvas {

    Color c;

    public MyCanvas(Color c) {
        setSize(30, 30);
        this.c = c;
    }


    @Override
    public void paint(Graphics g) {
        g.setColor(c);
        g.fillOval(0, 0, 30, 30);
    }
}

package org.base.practise9;

import java.awt.*;

/**
* Created with IntelliJ IDEA.
* User: cutter.li
* Date: 14-3-11
* Time: 上午10:32
* 面板對象,內含兩個球體線程,在油畫上面作位移
*/
public class MyFrame extends Frame implements Runnable {

    Thread red, blue;
    MyCanvas redC, blueC;
    double t = 0;

    public MyFrame() {
        this.red = new Thread(this);
        this.blue = new Thread(this);
        redC = new MyCanvas(Color.RED);
        blueC = new MyCanvas(Color.BLUE);

        setLayout(null);
        add(redC);
        add(blueC);
        redC.setLocation(60, 100);
        blueC.setLocation(60, 100);

        red.start();
        blue.start();

    }


    @Override
    public void run() {
        while (true) {
            int vo=80;
            t+=0.2;
            if(t>20){
                t=0;
            }
            Thread thread = Thread.currentThread();
            if (thread == red) {
                /**
                 *   S=Vot-0.5gt^2
                 */
                int x = 60;
                int y = (int)(t*vo- 0.5*9.8*t*t);
                redC.setLocation(x, y);

            } else if (thread == blue) {
                /**
                 * 水平方向位移x=V0cosα·t
                 4.豎直方向位移y=V0cosα·t-(1/2)*gt^2
                 */
                int x =(int) (Math.cos(45.0d)*t*vo);
                int y =(int) (Math.cos(45d)*t*vo-0.5*9.8*t*t);
                blueC.setLocation(x, y);


            }
            try {
                thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        }
    }
}

package org.base.practise9;

/**
* Created with IntelliJ IDEA.
* User: cutter.li
* Date: 14-3-11
* Time: 下午12:01
* To change this template use File | Settings | File Templates.
*/
public class People implements Runnable {


    Thread student1=new Thread(this);

    Thread student2=new Thread(this);

    Thread teacher=new Thread(this);

    public Thread getStudent1() {
        return student1;
    }

    public Thread getStudent2() {
        return student2;
    }

    public Thread getTeacher() {
        return teacher;
    }

    @Override
    public void run() {
        if(Thread.currentThread()==student1)
        {     System.out.println(student1.getName()+"在睡覺,打算睡10分鐘");
            try {
                student1.sleep(10*60*1000);
            } catch (InterruptedException e) {
               System.out.println("被老師叫醒...");
            }
            System.out.println(student1.getName()+"開始聽課");
            student2.interrupt();
        }else if(Thread.currentThread()==student2)
        {
            System.out.println(student2.getName()+"在睡覺,打算睡60分鐘");
            try {
                student2.sleep(60*60*1000);
            } catch (InterruptedException e) {
                System.out.println("被"+student1.getName()+"叫醒...");
            }
            System.out.println(student2.getName()+"開始聽課");
        }else if(Thread.currentThread()==teacher)
        {
            for(int i=1;i<=3;i++)
            {
                System.out.println("上課了");
                try {
                    teacher.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
           student1.interrupt();
        }
    }
}

package org.base.practise9;

/**
* Created with IntelliJ IDEA.
* User: cutter.li
* Date: 14-3-11
* Time: 上午11:13
* To change this template use File | Settings | File Templates.
*/
public class TicketSeller {

    int fiveCount=3,tenCount=0,twentyCount=0;

    public  synchronized void sellTicket(int money){
        if(money==5){
            fiveCount++;
            System.out.println("給你票,錢正好");
        }else if(money==20)
        {
            while((fiveCount<3&&tenCount<1)||(tenCount>1&&fiveCount<1))
            {
                try{
                    wait();
                } catch (InterruptedException ex)
                {

                }
            }

            if(tenCount>=1&&fiveCount>=1){
                fiveCount--;
                tenCount--;
                System.out.println("收你20塊,找回5塊1張,10塊1張");
            }else if(fiveCount>=3){
                fiveCount-=3;
                System.out.println("收你20塊,找回5塊3張");
            }


        }else if(money==10){
            while (fiveCount<1)
            {
                try{
                    wait();
                } catch (InterruptedException ex)
                {

                }
            }
            fiveCount--;
            tenCount++;
            System.out.println("收你10塊,找回5塊");

        }
        notifyAll();
    }

}

package org.base.practise9;

/**
* Created with IntelliJ IDEA.
* User: cutter.li
* Date: 14-3-11
* Time: 下午12:29
* To change this template use File | Settings | File Templates.
*/
public class Worker implements Runnable {


    Thread siji=new Thread(this);

    Thread banyun=new Thread(this);

    Thread cangguan=new Thread(this);


    public Thread getSiji() {
        return siji;
    }

    public Thread getBanyun() {
        return banyun;
    }

    public Thread getCangguan() {
        return cangguan;
    }

    @Override
    public void run() {

        Thread thread=Thread.currentThread();

        if(thread==siji){

            try {
                banyun.join();
            } catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }

            System.out.println("司機開始工做");

        } else  if(thread==banyun)
        {
            try {
                cangguan.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("搬運工開始工做");
        }  else if(thread==cangguan)
        {
            System.out.println("倉庫管理員打開倉庫");
        }

    }
}

經過練習,熟悉了線程的基本操做和概念,溫故而知新。

相關文章
相關標籤/搜索