java学习之路 之 多线程练习题

来源:互联网 发布:手机图纸算量软件 编辑:程序博客网 时间:2024/04/28 11:46
package com.atguigu.javase.thread;/** * 创建并启动一个线程的方法 * 1) 实现接口的方式 * 1) 写一个具体类, 实现Runnable接口, 并实现其中的run方法,这个run方法就是线程的入口方法 * 2) 创建这个类的对象, 并以这个对象为实参, 创建Thread类的对象 * 3) 调用Thread对象的start()方法 启动线程 * */public class HelloRunner implements Runnable {private int n;@Overridepublic void run() {for (n = 0; n < 100; n++) {System.out.println(Thread.currentThread().getName() + ":" + n);}}}package com.atguigu.javase.thread;public class HelloRunnerTest {public static void main(String[] args) {Runnable runnable = new HelloRunner();Thread thread = new Thread(runnable); // thread对象就是线程对象, 这个语句的执行相当于创建线程的栈//thread.run(); // 不会激活栈, 对于run方法只是一个普通方法调用thread.start();// 激活栈,并把run()方法压入栈底thread.setName("子线程1");/*Thread thread2 = new Thread(runnable);thread2.start();thread2.setName("子线程2");*/try {thread.join(); // 会引起当前线程阻塞, 直到子线程执行完毕} catch (InterruptedException e) {e.printStackTrace();} Thread.currentThread().setName("主线程");for (int i = 0; i < 100; i++) {System.out.println(Thread.currentThread().getName() + ":" + i);}}}import org.junit.Test;public class ThreadTest {//创建一个子线程,在线程中输出1-100之间的偶数,主线程输出1-100之间的奇数。@Testpublic void test() {Runnable print = new Print();Thread thread = new Thread(print);thread.setName("子线程---->");thread.start();Thread.currentThread().setName("主线程---->");for (int i = 0; i < 100; i++) {if (i % 2 != 0) {System.out.println(Thread.currentThread().getName() + i);}}}@Testpublic void test2() {Runnable print = new Print();Thread thread = new Thread(print);thread.setName("子线程1---->");thread.start();Runnable print1 = new Print1();Thread thread1 = new Thread(print1);thread1.setName("子线程2---->");thread1.start();}}class Print implements Runnable {@Overridepublic void run() {for (int i = 0; i < 100; i++) {if (i % 2 == 0) {System.out.println(Thread.currentThread().getName() + i);}}}}class Print1 implements Runnable {@Overridepublic void run() {for (int i = 0; i < 100; i++) {if (i % 2 != 0) {System.out.println(Thread.currentThread().getName() + i);}}}}package com.atguigu.javase.thread;/** * 创建线程的第二种方式: * 继承的方式 * 1) 写一个具体类继承自Thread, 重写run方法, 这个run方法是真的入口 * 2) 创建具体类对象, 相当于创建了Thread对象 * 3) 调用Thread对象的.start() */class TestThread extends Thread {@Overridepublic void run() {for (int i = 0; i < 100; i++) {System.out.println(currentThread().getName() + " : " + i);}}}public class ThreadTest {public static void main(String[] args) {new TestThread().start();for (int i = 0; i < 100; i++) {System.out.println(Thread.currentThread().getName() + ":" + i);}}}package com.atguigu.javase.thread;public class Counter implements Runnable {private int counter = 200;@Override//public synchronized void run() {public void run() {//synchronized (this) {// 锁的粒度大for (int i = 0; i < 50; i++) {//synchronized (锁对象) { // 锁对象必须是多个线程都使用同一个对象synchronized (System.in) {// 其中的语句具有原子性counter -= 2;try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName() + " : " + counter);}}}}package com.atguigu.javase.thread;public class CounterTest {public static void main(String[] args) {Counter counter = new Counter();Thread thread1 = new Thread(counter);thread1.setName("线程1");thread1.start();Thread thread2 = new Thread(counter);thread2.setName("线程2");thread2.start();}}package com.atguigu.javase.thread;import java.util.ArrayList;import java.util.List;// sleep方法的使用public class DataGetter implements Runnable {private boolean forOver = false;public boolean isForOver() {return forOver;}public void setForOver(boolean forOver) {this.forOver = forOver;}@Overridepublic void run() {List<Integer> list = new ArrayList<Integer>();for (int i = 0; i < 100; i++) {int rand = (int)(Math.random() * 100);System.out.println(rand);list.add(rand);int randTime = (int)(Math.random() * 200);try {Thread.sleep(randTime);} catch (InterruptedException e) {System.out.println("在小睡[" + randTime + "]时被唤醒 , 小不爽");}}forOver = true;System.out.println("要长睡30秒...");try {Thread.sleep(30 * 1000);} catch (InterruptedException e) {System.out.println("在睡30秒时被唤醒 , 很不爽");}for (int i = 0; i < list.size(); i++) {System.out.println(list.get(i));}}}package com.atguigu.javase.thread;public class DataGetterTest {public static void main(String[] args) {Runnable r = new DataGetter();Thread thread = new Thread(r);thread.start();Runnable r2 = new Monitor(r, thread);Thread thread2 = new Thread(r2);thread2.start();/*while (!((DataGetter)r).isForOver()) {try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}}thread.interrupt();*/}}package com.atguigu.javase.thread;public class SleepRunner implements Runnable {@Overridepublic void run() {for (int i = 0; i < 100; i++) {System.out.println(i);try {Thread.sleep(100);} catch (InterruptedException e) {System.out.println("在睡100毫秒时被打断");} }System.out.println("要睡20秒");try {Thread.sleep(20 * 1000);} catch (InterruptedException e) {System.out.println("在长睡时被打断, 很不爽");}System.out.println("睡起来了...");}}package com.atguigu.javase.thread;public class SleepRunnerTest {public static void main(String[] args) {Runnable r = new SleepRunner();Thread thread = new Thread(r);thread.start();try {Thread.sleep(10000);} catch (InterruptedException e) {e.printStackTrace();}thread.interrupt();}}package com.atguigu.javase.thread;public class CanStopRunner implements Runnable {private int n = 0;private boolean stopFlag = false;public boolean isStopFlag() {return stopFlag;}public void setStopFlag(boolean stopFlag) {this.stopFlag = stopFlag;}@Overridepublic void run() { // 不是真的入口, 真的入口永远是Thread类中的run,while (!stopFlag) {System.out.println(Thread.currentThread().getName() + " : " + n++);if (n == 100) {n = 0;}}System.out.println("after while...");}}package com.atguigu.javase.thread;public class CanStopTest {public static void main(String[] args) {Runnable r = new CanStopRunner();Thread t = new Thread(r);t.start();for (int i = 0; i < 1000000; i++) {int j = i + i;}// 线程的停止//t.stop();((CanStopRunner)r).setStopFlag(true); //以通知的方式停止线程}}package com.atguigu.javase.thread;public class RandomRunner implements Runnable {private boolean stopFlag;public boolean isStopFlag() {return stopFlag;}public void setStopFlag(boolean stopFlag) {this.stopFlag = stopFlag;}@Overridepublic void run() {while (!stopFlag) {System.out.println((int)(Math.random() * 100));}}}package com.atguigu.javase.thread;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;public class KeyListener implements Runnable {private Runnable r;public KeyListener(Runnable r) {this.r = r;}@Overridepublic void run() {InputStream is = System.in;InputStreamReader isr = null;BufferedReader bufferedReader = null;try {isr = new InputStreamReader(is);bufferedReader = new BufferedReader(isr);String line = bufferedReader.readLine();while (line != null) {// 1)if (line.equalsIgnoreCase("Q")) {((RandomRunner)r).setStopFlag(true);//break;}// 2)line = bufferedReader.readLine();}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();} finally {try {bufferedReader.close();} catch (Exception e2) {// TODO: handle exception}}}}package com.atguigu.javase.thread;public class RandomRunnerTest {//在main方法中创建并启动1个线程。线程循环随机打印100以内的整数,直到主线程从键盘读取了“Q”命令。//在main方法中创建并启动两个线程。第一个线程循环随机打印100以内的整数,直到第二个线程从键盘读取了“Q”命令。public static void main(String[] args) {Runnable r = new RandomRunner();Thread t = new Thread(r);t.start();Runnable r2 = new KeyListener(r);Thread t2 = new Thread(r2);t2.setDaemon(true);t2.start();/*InputStream is = System.in;InputStreamReader isr = null;BufferedReader bufferedReader = null;try {isr = new InputStreamReader(is);bufferedReader = new BufferedReader(isr);String line = bufferedReader.readLine();while (line != null) {// 1)if (line.equalsIgnoreCase("Q")) {((RandomRunner)r).setStopFlag(true);break;}// 2)line = bufferedReader.readLine();}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();} finally {try {bufferedReader.close();} catch (Exception e2) {// TODO: handle exception}}*/}}package com.atguigu.javase.thread;// 创建一个账户类 ,实现取钱与存钱的同步操作public class Account {private String name;private int balance;public Account() {}public Account(String name, int balance) {super();this.name = name;this.balance = balance;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getBalance() {return balance;}public void setBalance(int balance) {this.balance = balance;}@Overridepublic String toString() {return "Account [name=" + name + ", balance=" + balance + "]";}}package com.atguigu.javase.thread;// 存钱操作的处理public class Deposit implements Runnable {private Account account;public Deposit(Account account) {this.account = account;}@Overridepublic void run() {for (;;) {synchronized ("") {int rand = (int)(Math.random() * 1000);account.setBalance(account.getBalance() + rand);System.out.println("存钱[" + rand + "]后" + ":" + account);"".notifyAll();}try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}}package com.atguigu.javase.thread;// 取钱操作的处理public class Withdraw implements Runnable {private Account account;public Withdraw(Account account) {this.account = account;}@Overridepublic void run() {for (;;) {synchronized ("") {int rand = (int)(Math.random() * 100);while (rand > account.getBalance()) {try {"".wait();} catch (InterruptedException e) {e.printStackTrace();}}account.setBalance(account.getBalance() - rand);try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("取钱[" + rand + "]后:" + account);}}}}package com.atguigu.javase.thread;public class AccountTest {public static void main(String[] args) {Account account = new Account("张三", 1000);Runnable runnable1 = new Deposit(account);Runnable runnable2 = new Withdraw(account);Thread t1 = new Thread(runnable1);Thread t2 = new Thread(runnable2);t2.start();t1.start();}}package com.atguigu.javase.thread;// notify方法的使用public class PrintNumberRunner implements Runnable {private int i = 0;@Overridepublic void run() {for (;;) {synchronized ("") {"".notify(); // 必须是锁对象调用, 并且必须和wait方法的锁是同一把锁 并且此方法调用必须处于synchronized块中if (i == 100) {break;}i++;System.out.println(Thread.currentThread().getName() + " : " + i);try {"".wait(); // 必须是锁对象调用, 并且此方法调用必须处于synchronized块中} catch (InterruptedException e) {e.printStackTrace();}}}}public static void main(String[] args) {Runnable runnable = new PrintNumberRunner();Thread thread1 = new Thread(runnable);Thread thread2 = new Thread(runnable);thread1.start();thread2.start();}}package com.atguigu.javase.thread;public class TestDeadLock {// 死锁实例static StringBuffer s1 = new StringBuffer();static StringBuffer s2 = new StringBuffer();public static void main(String[] args) {new Thread() {public void run() {synchronized (s1) {s2.append("A");try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}synchronized (s2) {s2.append("B");System.out.print(s1);System.out.print(s2);}}}}.start();new Thread() {public void run() {synchronized (s2) {s2.append("C");synchronized (s1) {s1.append("D");System.out.print(s2);System.out.print(s1);}}}}.start();}}

2 0
原创粉丝点击