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

}
}

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

java基础知识 多线程的更多相关文章

  1. Java基础知识➣多线程编程(五)

    概述 Java 给多线程编程提供了内置的支持.一个多线程程序包含两个或多个能并发运行的部分.程序的每一部分都称作一个线程,并且每个线程定义了一个独立的执行路径.使用多线程也是为了充分的利用服务器资源, ...

  2. JAVA基础知识之网络编程——-网络基础(Java的http get和post请求,多线程下载)

    本文主要介绍java.net下为网络编程提供的一些基础包,InetAddress代表一个IP协议对象,可以用来获取IP地址,Host name之类的信息.URL和URLConnect可以用来访问web ...

  3. java基础知识小总结【转】

    java基础知识小总结 在一个独立的原始程序里,只能有一个 public 类,却可以有许多 non-public 类.此外,若是在一个 Java 程序中没有一个类是 public,那么该 Java 程 ...

  4. Java 基础知识总结

    作者QQ:1095737364    QQ群:123300273     欢迎加入! 1.数据类型:  数据类型:1>.基本数据类型:1).数值型: 1}.整型类型(byte  8位   (by ...

  5. Java基础知识回顾之七 ----- 总结篇

    前言 在之前Java基础知识回顾中,我们回顾了基础数据类型.修饰符和String.三大特性.集合.多线程和IO.本篇文章则对之前学过的知识进行总结.除了简单的复习之外,还会增加一些相应的理解. 基础数 ...

  6. Java基础知识总结(超级经典)

    Java基础知识总结(超级经典) 写代码: 1,明确需求.我要做什么? 2,分析思路.我要怎么做?1,2,3. 3,确定步骤.每一个思路部分用到哪些语句,方法,和对象. 4,代码实现.用具体的java ...

  7. 毕向东—Java基础知识总结(超级经典)

    Java基础知识总结(超级经典) 写代码: 1,明确需求.我要做什么? 2,分析思路.我要怎么做?1,2,3. 3,确定步骤.每一个思路部分用到哪些语句,方法,和对象. 4,代码实现.用具体的java ...

  8. Java 基础知识总结1

    作者QQ:1095737364    QQ群:123300273     欢迎加入! 1.数据类型:  数据类型:1>.基本数据类型:1).数值型: 1}.整型类型(byte  8位   (by ...

  9. 沉淀,再出发:Java基础知识汇总

    沉淀,再出发:Java基础知识汇总 一.前言 不管走得多远,基础知识是最重要的,这些知识就是建造一座座高楼大厦的基石和钢筋水泥.对于Java这门包含了编程方方面面的语言,有着太多的基础知识了,从最初的 ...

随机推荐

  1. Swift enum(枚举)使用范例

    //: Playground - noun: a place where people can play import UIKit var str = "Hello, playground& ...

  2. Javascript 代理模式模拟一个文件同步功能

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  3. C# 给word文档添加水印

    和PDF一样,在word中,水印也分为图片水印和文本水印,给文档添加图片水印可以使文档变得更为美观,更具有吸引力.文本水印则可以保护文档,提醒别人该文档是受版权保护的,不能随意抄袭.前面我分享了如何给 ...

  4. C++整数转字符串的一种方法

    #include <sstream> //ostringstream, ostringstream::str() ostringstream stream; stream << ...

  5. Android—Service与Activity的交互

    service-Android的四大组件之一.人称"后台服务"指其本身的运行并不依赖于用户可视的UI界面 实际开发中我们经常需要service和activity之间可以相互传递数据 ...

  6. MySQL加密

    MySQL字段加密和解密 1.加密:aes_encrypt('admin','key') 解密:aes_decrypt(password,'key') 2.双向加密 通过密钥去加密,解密的时候的只有知 ...

  7. 【Java并发编程实战】----- AQS(一):简介

    在前面博客中,LZ讲到了ReentrantLock.ReentrantReadWriteLock.Semaphore.CountDownLatch,他们都有各自获取锁的方法,同时相对于Java的内置锁 ...

  8. [异常解决] How to build a gcc toolchain for nRF51 on linux (very detailed!!!)

    1.Install gcc-arm-none-eabi https://devzone.nordicsemi.com/tutorials/7/This link shows that developm ...

  9. TODO:Go语言goroutine和channel使用

    TODO:Go语言goroutine和channel使用 goroutine是Go语言中的轻量级线程实现,由Go语言运行时(runtime)管理.使用的时候在函数前面加"go"这个 ...

  10. TODO:MongoDB的查询更新删除总结

    TODO:MongoDB的查询更新删除总结 常用查询,条件操作符查询,< .<=.>.>=.!= 对应 MongoDB的查询操作符是$lt.$lte.$gt.$gte.$ne ...