目录
Java面向对象 - 文件类
第1关:创建文件:
package step1;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Scanner;
public class Task {
/********* Begin *********/
public void solution(){
try{
File f1 = new File("src/output/test.txt");
File f2 = new File("src/output/hello.txt");
f1.createNewFile();
f2.createNewFile();
boolean isf1 = f1.exists();
boolean isf2 = f2.exists();
}catch(IOException e){
e.printStackTrace();
}
/********* End *********/
}
}
第2关:文件的常用操作:
package step2;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Arrays;
public class Task {
public static void dcFile() throws IOException {
/********* Begin *********/
try{
File f1 = new File("src/test2");
f1.mkdir();
File f2 = new File("src/output/test2.txt");
f2.delete();
File f3 = new File("src/test2/helloworld.txt");
File f4 = new File("src/test2/step2.txt");
f3.createNewFile();
f4.createNewFile();
System.out.println("output目录结构为:");
File dir1 = new File("src/output");
File[] files1 = dir1.listFiles();
Arrays.sort(files1);
for(File file : files1){
System.out.println(file.getName());
}
System.out.println("test2目录结构为:");
File dir2 = new File("src/test2");
File[] files2 = dir2.listFiles();
Arrays.sort(files2);
for(File file : files2){
System.out.println(file.getName());
}
}catch(IOException e){
e.printStackTrace();
}
/********* End *********/
}
}
第3关:文件查看器
package step3;
import java.io.File;
import java.util.Arrays;
public class Task {
/********** Begin **********/
int n=1;//记录缩进层数
public void showDirStructure(File file) {
System.out.println("+--"+file.getName());
File[] dir = file.listFiles();
Arrays.sort(dir);
for(File files:dir)
{
if(files.isDirectory())
{
for(int i=0;i<n*2;++i) System.out.print(" ");
++n;//若是文件夹则需要缩进2个空格
showDirStructure(files);
--n;//递归完成后返回上一层缩进。
}
else
{
for(int i=0;i<n*2;++i) System.out.print(" ");
System.out.println("--"+files.getName());
}
}
}
/********** End **********/
}
第4关:图片查看器
package step4;
import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
public class Task {
/********** Begin **********/
public void showDirStructure(File file) {
if (file.isDirectory()){//这里是对于输入文件夹(传递参数file对象)刚开始的操作
System.out.println("+--"+file.getName());//对于此文件夹+--输出
}
int a=2; //定义int整数为2,作为输出空格的个数,此时第一层已经输出 故传入2
showDirTree(a,file);//调用递归函数
}
public void showDirTree(int a,File file){
//传入文件夹
File[] files=file.listFiles();//获取该文件夹下的所有文件数组
Arrays.sort(files);//将所有文件数组进行升序排列
for (int i=0;i<files.length;i++){ //for循环对于所获取的数组循环输入
if (files[i].isDirectory()){//判断是否为文件夹
for(int j=0;j<a;j++){
System.out.print(" ");//输出空格,第一次为2,与传入的a相关
}
System.out.println("+--"+files[i].getName());//输出文件夹名称
showDirTree(a+2,files[i]);//继续调用函数,a+2进入下一层
}else{//递归调用出口
String fileName = files[i].getName().toLowerCase();//将数组文件名转换为字符串
if (fileName.endsWith(".jpg")||fileName.endsWith(".png")||fileName.endsWith(".bmp")){
//判断是否为.jpg .png .bmp文件名后缀,是才输出
for(int j=0;j<a;j++){
System.out.print(" ");//for循环输出空格
}
System.out.println("--"+files[i].getName());//输出文件名
}
}
}
}
/********** End **********/
// public void showDirStructure(File file) {
// //创建文件过滤器
// FileFilter filter = file -> {
// if(file.isFile()){
// String filename = file.getName().toLowerCase();
// if(filename.endWith(".jpg") || filename.endWith(".png") || filename.endWith(".bmp"))
// return true;
// else
// return false;
// }else{
// }
// }
// int n = 1;//记录缩进层数
// System.out.println("+--"+file.getName());
// File[] dir = file.listFiles();
// Arrays.sort(dir);
// for(File files:dir)
// {
// if(files.isDirectory())
// {
// for(int i=0;i<n*2;++i) System.out.print(" ");
// ++n;//若是文件夹则需要缩进2个空格
// showDirStructure(files);
// --n;//递归完成后返回上一层缩进。
// }
// else
// {
// for(int i=0;i<n*2;++i) System.out.print(" ");
// System.out.println("--"+files.getName());
// }
// }
// }
}
Java高级特性 - IO流
第1关:什么是IO流
bc
c
第2关:字节流-输入输出
package step2;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Task {
public void task() throws IOException{
/********* Begin *********/
File file1 = new File("src/step2/input/task.txt");
InputStream fs = new FileInputStream(file1);
byte[] b1 = new byte[1024];
fs.read(b1);
String str1 = new String(b1, "utf-8");
System.out.print(str1);
fs.close();
File file = new File("src/step2/output");
if(!file.exists()){
file.mkdir();
}
String file2 = "src/step2/output/output.txt";
OutputStream out = new FileOutputStream(file2);
String str2 = "learning practice";
byte[] b2 = str2.getBytes(); //字符转化成字节
out.write(b2);
out.flush(); //刷新缓冲区数据(类似保存数据)
out.close();
/********* End *********/
}
}
第3关:字符流 - 输入输出
package step3;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.File;
public class Task {
public void task() throws IOException{
/********* Begin *********/
// 将src/step3/input/目录下的input.txt文件复制到src/step3/output/目录下;
// 复制的新文件命名为output.txt;
// input.txt文件中只有8个字符。
String file = "src/step3/input/input.txt";
FileReader fr = new FileReader(file);
char[] cbuf = new char[8];
fr.read(cbuf);
File wfile = new File("src/step3/output/output.txt");
FileWriter fw = new FileWriter(wfile);
fw.write(cbuf);
fr.close();
fw.flush();
fw.close();
/********* End *********/
}
}
第4关:复制文件
package step4;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
public class Task {
public void task() throws IOException{
/********* Begin *********/
// BufferedReader bf = new BufferedReader(new FileReader("src/step4/input/input.txt"));
// BufferedWriter writer = new BufferedWriter(new FileWriter("src/step4/output/output.txt"));
// String str = "";
// while( (str = bf.readLine()) != null){
// writer.write(str);
// }
// bf.close();
// writer.close();
FileReader fr = new FileReader("src/step4/input/input.txt"); //定义FileReader读取文件
int l = 0; //每次读取的字符数量
char[] cbuf = new char[1024]; //每次读取数据的缓冲区
FileWriter fw = new FileWriter("src/step4/output/output.txt"); //定义FileWriter写文件
while((l = fr.read(cbuf)) != -1){
fw.write(cbuf,0,l);
}
fw.close(); //释放资源 刷新缓冲区
fr.close();
FileInputStream fs = new FileInputStream("src/step4/input/input.jpg");
FileOutputStream fos = new FileOutputStream("src/step4/output/output.jpg");
int len = 0;
byte[] bys = new byte[1024];
while( (len = fs.read(bys)) != -1){
fos.write(bys, 0, len);
}
fs.close();
fos.close();
/********* End *********/
}
}
Java高级特性 - JDBC(上)
第1关:JDBC连接数据库
package jdbc;
import java.sql.*;
public class jdbcConn {
public static void getConn() {
/********** Begin **********/
try {
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
/********** End **********/
/********** Begin **********/
Connection conn = null;
Statement statement = null;
//2.建立连接并创建数据库和表
String url= "jdbc:mysql://localhost:3306/";
String user = "root";
String password = "123123";
//建立连接
try{
conn = DriverManager.getConnection(url,user,password);
} catch(Exception e){
e.printStackTrace();
}
//创建 statement 对象
try{
statement = conn.createStatement();
} catch(SQLException e){
e.printStackTrace();
}
//创建数据库
try{
String sql1 = "drop database if exists mysql_db";
String sqlcreatedatabase = "create database mysql_db";
statement.executeUpdate(sql1);
statement.executeUpdate(sqlcreatedatabase);//执行sql语句
}catch(SQLException e){
e.printStackTrace();
}
//创建表 :
try{
statement.executeUpdate("use mysql_db");
String sql = "create table student(id int,name varchar(20),sex varchar(4),age int); ";
statement.executeUpdate(sql);
}catch(SQLException e){
e.printStackTrace();
}
/********** End **********/
finally {
try {
if(statement!=null)
statement.close();
if(conn!=null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
第2关:JDBC对表中数据的操作
package jdbc;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class jdbcInsert {
public static void insert(){
/********** Begin **********/
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
/********** End **********/
Connection conn = null;
PreparedStatement statement = null;
/********** Begin **********/
try{
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mysql_db","root","123123");
statement = conn.prepareStatement("insert into student values(?,?,?,?)");
statement.setInt(1,1);
statement.setString(2,"张三");
statement.setString(3,"男");
statement.setInt(4,19);
statement.executeUpdate();
statement.setInt(1,2);
statement.setString(2,"李四");
statement.setString(3,"女");
statement.setInt(4,18);
statement.executeUpdate();
statement.setInt(1,3);
statement.setString(2,"王五");
statement.setString(3,"男");
statement.setInt(4,20);
statement.executeUpdate();
statement = conn.prepareStatement("select * from student");
ResultSet r = statement.executeQuery();
while(r.next()){
System.out.println(r.getString(1)+" "+r.getString(2)+" "+r.getString(3)+" "+r.getString(4));
}
}catch(SQLException e){
e.printStackTrace();
}
/********** End **********/
finally {
try {
if (statement != null)
statement.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
第3关:JDBC事务
package jdbc;
import java.sql.*;
public class jdbcTransaction {
public static void transaction(){
try {
Class.forName("com.mysql.jdbc.Driver" );
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection conn = null;
PreparedStatement ps = null;
String url = "jdbc:mysql://localhost:3306/mysql_db";
/********** Begin **********/
//连接数据库并开启事务
try {
conn = DriverManager.getConnection(url,"root","123123");
conn.setAutoCommit(false);
String sql = "insert into student(id,name,sex,age) values(4,'赵六','女',21)";
ps = conn.prepareStatement(sql);
ps.executeUpdate();
conn.commit();
ps = conn.prepareStatement("5yss214401206");
ps.executeUpdate();
conn.commit();
String sqlm = "select * from student";
ResultSet r = ps.executeQuery(sqlm);
while(r.next()){
System.out.println(r.getString(1)+" "+r.getString(2)+" "+r.getString(3)+" "+r.getString(4));
}
} catch (SQLException e) {
try {
//事务回滚
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
/********** End **********/
finally {
try {
if(ps!=null)
ps.close();
if (conn != null)
conn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
}
Java高级特性 - JDBC(下)
第1关:指定类型JDBC封装
package step1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import test.News;
public class JDBCUtils {
/**
* 连接数据库
*/
private static Connection getConnection() {
Connection conn=null;
/********** Begin **********/
String url="jdbc:mysql://localhost:3306/mysql_db";
try {
Class.forName("com.mysql.jdbc.Driver" );
conn = DriverManager.getConnection(url,"root","123123");
}catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}
/********** End **********/
return conn;
}
/**
* 更新数据方法
* @param news
* @throws SQLException
*/
public void update(News news) throws SQLException {
Connection conn = getConnection();
PreparedStatement ps = null;
/********** Begin **********/
String sql = "update news set title = ?,author_name = ? where id = ?";
try{
ps = conn.prepareStatement(sql);
ps.setString(1,news.getTitle());
ps.setString(2,news.getAuthor_name());
ps.setInt(3,news.getId());
ps.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
throw new SQLException("更新数据失败");
}finally{
close(null, ps, conn);
}
/********** End **********/
}
/**
* 查询所有数据
* @return
* @throws SQLException
*/
public List<News> findAll() throws SQLException {
Connection conn = getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
News news = null;
List<News> newsList = new ArrayList<News>();
/********** Begin **********/
String sql = "select * from news";
try{
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
news = new News();
news.setId(rs.getInt(1));
news.setTitle(rs.getString(2));
news.setAuthor_name(rs.getString(3));
newsList.add(news);
}
}catch(SQLException e){
e.printStackTrace();
throw new SQLException("查询所有数据失败");
}finally{
close(rs, ps, conn);
}
/********** End **********/
return newsList;
}
/**
* 删除方法
* @param id
* @throws SQLException
*/
public void delete(int id) throws SQLException{
Connection conn = getConnection();
PreparedStatement ps = null;
/********** Begin **********/
String sql = "delete from news where id = ?";
try{
ps = conn.prepareStatement(sql);
ps.setInt(1,id);
ps.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
throw new SQLException(" 删除数据失败");
}
finally{
close(null, ps, conn);
}
/********** End **********/
}
/**
* 增加对象
* @param news
* @throws SQLException
*/
public void insert(News news) throws SQLException {
Connection conn = getConnection();
PreparedStatement ps = null;
String sql = "insert into news(id,title,author_name)values(?,?,?)";
try{
ps = conn.prepareStatement(sql);
ps.setInt(1, news.getId());
ps.setString(2, news.getTitle());
ps.setString(3, news.getAuthor_name());
ps.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
throw new SQLException("添加数据失败");
}finally{
close(null, ps, conn);
}
}
/**
* 根据id查询对象
* @param id
* @return
* @throws SQLException
*/
public News findById(int id) throws SQLException {
Connection conn = getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
News news = null;
String sql = "select * from news where id=?";
try{
ps = conn.prepareStatement(sql);
ps.setInt(1, id);
rs = ps.executeQuery();
if(rs.next()){
news = new News();
news.setId(id);
news.setTitle(rs.getString(2));
news.setAuthor_name(rs.getString(3));
}
}catch(SQLException e){
e.printStackTrace();
throw new SQLException("根据ID查询数据失败");
}
finally{
close(rs, ps, conn);
}
return news;
}
/**
* 关闭数据库连接
* @param rs
* @param ps
* @param conn
*/
public static void close(ResultSet rs,PreparedStatement ps,Connection conn){
try {
if(rs!=null)rs.close();
if(ps!=null)ps.close();
if(conn!=null)conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
第2关:泛型JDBC封装
package step2;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class JDBCUtils {
private static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String url="jdbc:mysql://localhost:3306/mysql_db";
Connection conn=null;
try {
conn = DriverManager.getConnection(url, "root","123123");
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* 类名对应表,属性对应字段
* @param obj 传入的对象
* @return
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public void insert(Object obj){
Connection conn = getConnection(); //连接数据库
PreparedStatement ps = null;
/********** Begin **********/
Class<?> c = obj.getClass();//获取obj的Class
StringBuffer sb = new StringBuffer("insert into "+ c.getSimpleName());//利用StringBuffer进行修改SQL语句的构造
Field[] field = c.getDeclaredFields();//通过反射获取对象的属性数组
for(int i=0;i<field.length;i++) {
if(i==0) {
sb.append("(").append(field[i].getName()).append(",");
}else if(i!=field.length-1) {
sb.append(field[i].getName()).append(",");
}else {
sb.append(field[i].getName()).append(")");
}
}
for(int i = 0; i < field.length; i++) {
if(i==0){
sb.append("values(").append("?,");
}else if(i != field.length-1) { //判断是否为最后一个属性,若不是则后增加逗号
sb.append("?,");
}else { //若为最后一个属性则添加 where
sb.append("?)");
}
}
//默认第一个属性为主键,切更改时通过第一个属性进行更改
String sql = sb.toString()+";";
try {
ps = conn.prepareStatement(sql);
for(int i = 0; i < field.length; i++) {
field[i].setAccessible(true);//设置可以访问私有属性
try {
ps.setObject(i+1, field[i].get(obj));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}//对预编译的SQL语句中的 ? 进行赋值
}
ps.execute();//执行sql语句
}
/********** End **********/
catch (SQLException e) {
e.printStackTrace();
}finally {
close(null,ps,conn);
}
}
/**
* 通过对象的Class获取对应表中的所有记录
* @param c
* @return
* @throws IllegalAccessException
* @throws InstantiationException
*/
public <T> List<T> selectAll(Class<T> c){
Connection conn = getConnection();
List<T> list = new ArrayList<T>();
PreparedStatement ps = null;
ResultSet rs = null;
/********** Begin **********/
String sql = "select * from "+c.getSimpleName();
Field[] fields= c.getDeclaredFields();
T t;
try {
ps = conn.prepareStatement(sql);
rs=ps.executeQuery();
while(rs.next()) {
/**
* t的实例化必须放在循环中,放在循环外会出现所有数据都是最后一个;
*/
t = c.newInstance();
for(int i=0;i<fields.length;i++) {
fields[i].setAccessible(true);
fields[i].set(t, rs.getObject(i+1));
}
list.add(t);
}
/********** End **********/
}catch (Exception e) {
e.printStackTrace();
}finally {
close(rs,ps,conn);
}
return list;
}
/**
* 通过主键(默认第一个属性)删除对象
* @param obj
* @return
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public void delete(Object obj){
Connection conn = getConnection();
PreparedStatement ps = null;
/********** Begin **********/
Class c = obj.getClass();
Field[] fields = c.getDeclaredFields();
String sql = "delete from "+c.getSimpleName()+" where "+fields[0].getName()+"=?;";
try {
ps = conn.prepareStatement(sql);
fields[0].setAccessible(true);
ps.setObject(1, fields[0].get(obj));
ps.execute();
}
/********** End **********/
catch (Exception e) {
e.printStackTrace();
}finally {
close(null,ps,conn);
}
}
/**
* 模拟jdbc的更新操作,默认第一个属性为主键
* @param obj
* @return
*/
public void update(Object obj) {
Class<?> c = obj.getClass();//获取obj的Class
StringBuffer sb = new StringBuffer("update "+ c.getSimpleName() +" set ");//利用StringBuffer进行修改SQL语句的构造
Field[] field = c.getDeclaredFields();//通过反射获取对象的属性数组
for(int i = 1; i < field.length; i++) {
if(i != field.length-1) { //判断是否为最后一个属性,若不是则后增加逗号
sb.append(field[i].getName()).append("=?,");
}else { //若为最后一个属性则添加 where
sb.append(field[i].getName()).append("=? where ");
}
}
//默认第一个属性为主键,切更改时通过第一个属性进行更改
sb.append(field[0].getName() + "=?");
String sql = sb.toString()+";";
Connection conn = getConnection();//获取连接对象
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
for(int i = 1; i < field.length; i++) {
field[i].setAccessible(true);//设置可以访问私有属性
ps.setObject(i, field[i].get(obj));//对预编译的SQL语句中的 ? 进行赋值
}
field[0].setAccessible(true);
ps.setObject(field.length, field[0].get(obj));
ps.execute();//执行sql语句
} catch (Exception e) {
e.printStackTrace();
}finally {
close(null,ps,conn);//关闭连接数据
}
}
public static void close(ResultSet rs,PreparedStatement ps,Connection conn){
try {
if(rs!=null) rs.close();
if(ps!=null) ps.close();
if(conn!=null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public <T> Object selectById(Class<T> c,int id) {
String sql = "select * from "+ c.getSimpleName()+" where id="+id;
Field[] field = c.getDeclaredFields();
Connection conn = getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
Object obj=null;
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
obj = c.newInstance();
while(rs.next()) {
for(int i = 0; i < field.length; i++) {
field[i].setAccessible(true);
field[i].set(obj, rs.getObject(field[i].getName()));
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
close(rs,ps,conn);
}
return obj;
}
}
Java高级特性 - 多线程基础(1)使用线程
第1关:创建线程
package step1;
//请在此添加实现代码
/********** Begin **********/
public class ThreadClassOne extends Thread {
public void run()
{
for(int i=1;i<=9;i++)
{
if(i % 2 == 1){
System.out.print( i +" ");
}
}
}
}
/********** End **********/
package step1;
//请在此添加实现代码
/********** Begin **********/
public class ThreadClassTwo implements Runnable {
public void run()
{
for(int i = 0;i<=10;i++){
if(i%2 == 0){
System.out.print(i + " ");
}
}
}
}
/********** End **********/
第2关:使用 Callable 和 Future 创建线程
package step2;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class Task {
public void runThread(int num) {
//请在此添加实现代码
/********** Begin **********/
// 在这里开启线程 获取线程执行的结果
ThreadCallable t1=new ThreadCallable(num);
FutureTask<Integer> ft1=new FutureTask<>(t1);
Thread thread1=new Thread(ft1,"thread1");
thread1.start();
try{
System.out.println("线程的返回值为:"+ft1.get());
}catch(Exception e){
e.printStackTrace();
}
/********** End **********/
}
}
//请在此添加实现代码
/********** Begin **********/
/* 在这里实现Callable接口及方法 */
class ThreadCallable implements Callable<Integer> {
int num;
ThreadCallable(int num){
this.num=num;
}
ThreadCallable(){
}
public Integer call() throws Exception{
return getNum(num);
}
private int getNum(int num){
if(num<3){
return 1;
}
else{
return getNum(num-1)+getNum(num-2);
}
}
}
/********** End **********/
Java高级特性 - 多线程基础(2)常用函数
第1关:线程的状态与调度
ABC
D
A
B
D
ABD
第2关:常用函数(一)
package step2;
import java.util.Scanner;
public class Task {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
//请在此添加实现代码
/********** Begin **********/
Thread t = new MyThread("子线程",num);
t.start();
/********** End **********/
}
}
//请在此添加实现代码
/********** Begin **********/
class MyThread extends Thread{
private int num;
private String name;
public MyThread(String name,int num){
this.num=num;
this.name=name;
}
public void run(){
int[] arr = new int[2];
arr[0] = 1;
arr[1] = 1;
for (int i = 2; i < num; i++) {
int tmp = arr[1];
arr[1] = arr[0] + arr[1];
arr[0] = tmp;
}
System.out.println("子线程计算结果为:"+arr[1]);
}
}
/********** End **********/
第3关:常用函数(二)
package step3;
public class MyThread implements Runnable {
//请在此添加实现代码
/********** Begin **********/
private String name;
private Object prev;
private Object self;
private MyThread(String name,Object prev,Object self){
this.name = name;
this.prev = prev;
this.self = self;
}
public void run(){
int count = 5;
while(count>0){
synchronized(prev){
synchronized(self){
System.out.print(name);
count--;
self.notify();
}
try {
prev.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.exit(0);
}
public static void main(String[] args) throws Exception {
Object a = new Object();
Object b = new Object();
Object c = new Object();
MyThread ta = new MyThread("E",c,a);
MyThread tb = new MyThread("D",a,b);
MyThread tc = new MyThread("U",b,c);
new Thread(ta).start();
Thread.sleep(100);
new Thread(tb).start();
Thread.sleep(100);
new Thread(tc).start();
Thread.sleep(100);
}
/********** End **********/
}
Java高级特性 - 多线程基础(3)线程同步
第1关:并发编程的三个概念
ABD
AB
E
第2关:使用synchronized关键字同步线程
package step2;
public class Task {
public static void main(String[] args) {
final insertData insert = new insertData();
for (int i = 0; i < 3; i++) {
new Thread(new Runnable() {
public void run() {
insert.insert(Thread.currentThread());
}
}).start();
}
}
}
class insertData{
public static int num =0;
/********* Begin *********/
public synchronized void insert(Thread thread){
for (int i = 0; i <= 5; i++) {
num++;
System.out.println(num);
}
}
/********* End *********/
}
第3关:使用线程锁(Lock)实现线程同步
package step3;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Task {
public static void main(String[] args) {
final Insert insert = new Insert();
Thread t1 = new Thread(new Runnable() {
public void run() {
insert.insert(Thread.currentThread());
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
insert.insert(Thread.currentThread());
}
});
Thread t3 = new Thread(new Runnable() {
public void run() {
insert.insert(Thread.currentThread());
}
});
// 设置线程优先级
// t1.setPriority(Thread.MAX_PRIORITY);
// t2.setPriority(Thread.NORM_PRIORITY);
// t3.setPriority(Thread.MIN_PRIORITY);
t1.start();
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
t3.start();
}
}
class Insert {
public static int num;
// 在这里定义Lock
private Lock lock = new ReentrantLock();
public void insert(Thread thread) {
/********* Begin *********/
if(lock.tryLock()){
try{
System.out.println(thread.getName()+"得到了锁");
for (int i = 0; i < 5; i++) {
num++;
System.out.println(num);
}
}finally{
System.out.println(thread.getName()+"释放了锁");
lock.unlock();
}
}else{
System.out.println(thread.getName()+"获取锁失败");
}
}
/********* End *********/
}
第4关:使用volatile实现变量的可见性
//方法1:
package step4;
public class Task {
public volatile int inc = 0;
//请在此添加实现代码
/********** Begin **********/
public synchronized void increase() {
inc++;
}
/********** End **********/
public static void main(String[] args) {
final Task test = new Task();
for (int i = 0; i < 10; i++) {
new Thread() {
public void run() {
for (int j = 0; j < 1000; j++)
test.increase();
};
}.start();
}
while (Thread.activeCount() > 1) // 保证前面的线程都执行完
Thread.yield();
System.out.println(test.inc);
}
}
Java高级特性 - 多线程练习题
第1关:顺序输出
package step1;
public class Task {
public static void main(String[] args) throws Exception {
/********* Begin *********/
//在这里创建线程, 开启线程
Object a = new Object();
Object b = new Object();
Object c = new Object();
MyThread ta = new MyThread("A",c,a);
MyThread tb = new MyThread("B",a,b);
MyThread tc = new MyThread("C",b,c);
ta.start();
ta.sleep(100);
tb.start();
tb.sleep(100);
tc.start();
tc.sleep(100);
/********* End *********/
}
}
class MyThread extends Thread {
/********* Begin *********/
private String threadName;
private Object prev;
private Object self;
public MyThread(String name,Object prev,Object self){
this.threadName = name;
this.prev = prev;
this.self = self;
}
public void run() {
int count = 5;
while(count>0){
synchronized(prev){
synchronized(self){
System.out.println("Java Thread"+this.threadName+this.threadName);
count--;
self.notify();
}
try {
prev.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.exit(0);
}
/********* End *********/
}
第2关:售票窗口
package step2;
/********* Begin *********/
//定义站台类,实现卖票的功能。
public class Station extends Thread{
static int tick = 20; // 为了保持票数的一致,票数要静态
static Object ob = new Object(); // 创建一个静态钥匙 值是任意的
public void ticket() {
System.out.println( "卖出了第" + tick + "张票");
tick--;
}
public void run() {
while (tick > 0) {
synchronized (ob) {
if (tick > 0) {
ticket();
}
}
if(tick == 0){
System.out.println("票卖完了");
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}
}
/********* End *********/