正在回答 回答被采纳积分+1
3回答
John_Chentao
2017-10-01 17:45:56
package com.imooc.join; class MyThread_ extends Thread{ public void run() { for(int i=0;i<100;i++) { System.out.println(getName()+"正在执行"+(i+1)); } } } public class join { public static void main(String[] args) { // TODO Auto-generated method stub MyThread_ mt = new MyThread_ (); MyThread_ mt1= new MyThread_(); mt.start(); mt1.start(); try { mt.join(); mt1.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(int i=0; i<20;i++) { System.out.println("主线程运行第"+i); } System.out.println("主线程运行结束"); } }可以试下,执行后两个线程是交替执行的。并不是线程一执行后再执行线程二
一介农夫
2017-09-24 16:00:26
package threadsysnc; public class Bank { private String username; private double yue; public Bank(String username, double yue) { setUsername(username); setYue(yue); } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public double getYue() { return yue; } public void setYue(double yue) { this.yue = yue; } public void saveDeposit() { synchronized (this) { for (int n = 0; n < 5; n++) { int i = 100; this.setYue(this.getYue() + i); System.out.println("存款後的餘額爲:" + this.getYue()); } } } public void withDrawals() { synchronized (this) { for (int n = 0; n < 5; n++) { int i = 100; this.setYue(this.getYue() - i); System.out.println("取款後的餘額爲:" + this.getYue()); } } } }
package threadsysnc; public class SaveDeposit implements Runnable { Bank bank; public SaveDeposit(Bank bank) { this.bank = bank; } @Override public void run() { bank.saveDeposit(); } }
package threadsysnc; public class WithDrawals implements Runnable { Bank bank; public WithDrawals(Bank bank) { this.bank = bank; } @Override public void run() { bank.withDrawals(); } }
package threadsysnc; public class Test { public static void main(String[] args) { Bank bank = new Bank("1001", 5000); Thread savethread = new Thread(new SaveDeposit(bank)); Thread wiThread = new Thread(new WithDrawals(bank)); savethread.start(); wiThread.start(); } }
僅供參考
Java零基础入门18
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星