java基础知识 多线程

时间:2021-05-17 05:04:55

package org.base.practise9;

import org.junit.Test;

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

/**
* Created with IntelliJ IDEA.
* User: cutter.li
* Date: 14-3-11
* Time: 上午9:40
* 多线程基础知识练习
*/
public class PractiseTest {

//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() {

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

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("仓库管理员打开仓库");
        }

}
}

通过练习,熟悉了线程的基本操作和概念,温故而知新。