Java中的双线程不是多线程
我的代码:Java中的双线程不是多线程,java,multithreading,Java,Multithreading,我的代码: Test.java public class Test { public static void main(String[] args) { Account acc = new Account(); Thread1 t1 = new Thread1(acc); Thread2 t2 = new Thread2(acc); Thread t = new Thread(t2); t1.start(); t.sta
Test.java
public class Test {
public static void main(String[] args) {
Account acc = new Account();
Thread1 t1 = new Thread1(acc);
Thread2 t2 = new Thread2(acc);
Thread t = new Thread(t2);
t1.start();
t.start();
/*
for(int i=0;i<10;i++){
System.out.println("Main Thread : "+i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
}
}
Test.java
公开课考试{
公共静态void main(字符串[]args){
账户acc=新账户();
螺纹1 t1=新螺纹1(acc);
螺纹2 t2=新螺纹2(acc);
螺纹t=新螺纹(t2);
t1.start();
t、 start();
/*
对于(inti=0;i我相信您的代码是并行运行的
考虑到迭代次数太少,我认为您实际上不会遇到任何竞争条件。我建议您在代码中加入随机休眠,或者使用一些锁来引发人为争用
也可以考虑命名你的线程,并连接<代码> jVisalVM 应用程序来检查你的运行线程。< /P> < P>无法控制线程的运行顺序。调度器调度线程并运行它们。然而,我们可以在线程运行时设置睡眠序列。它将线程从运行状态转换为就绪状态和调度程序。我可以同时安排另一个线程。
Thread.sleep(300)//300是以毫秒为单位的时间
你应该首先自己调试你的代码。如果你真的弄不明白,你需要创建一个,这是太多的代码了。另外,在创建一个的过程中,你经常会发现你自己的错误。它们是线程。除非你以某种方式同步它们的操作,否则它们是独立执行的。Thread.sleep()是允许竞争条件的代码气味。考虑使用AN并将它以期望的顺序递送和存入任务。否则,定义所需的顺序,并在包<代码> java。UTIL并发<代码>中使用同步机制来执行它。作为一个旁注,请考虑不要误导性地命名可运行的“代码”>线程2。
,当它不是线程时。好的,谢谢@UnholySheepthanks@和ythomas非常感谢@samop。OP的代码已经在使用thread.sleep()
。使用thread.sleep()
通常是一种代码味道,因为它不能保证多个独立线程之间的任何执行顺序。
public class Thread1 extends Thread {
Account acc;
public Thread1(Account acc){
super();
this.acc=acc;
}
@Override
public void run() {
for(int i=0;i<10;i++){
acc.withdraw(100);
}
}
}
public class Thread2 implements Runnable {
Account acc;
public Thread2(Account acc){
super();
this.acc=acc;
}
public void run() {
for(int i=0;i<10;i++){
acc.deposit(100);
}
}
}
public class Account {
volatile int balance = 500;
public synchronized void withdraw(int amount){
try {
if(balance<=0){
wait();
}
balance=balance-amount;
Thread.sleep(100);
System.out.println("Withdraw : "+balance);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void deposit(int amount){
try {
balance = balance+amount;
Thread.sleep(100);
System.out.println("Deposit : "+balance);
notify();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
OUTPUT:
Withdraw : 400
Withdraw : 300
Withdraw : 200
Withdraw : 100
Withdraw : 0
Deposit : 100
Deposit : 200
Deposit : 300
Deposit : 400
Deposit : 500