楼主的问题原理可以上网找找资料。我给你提供个例子。或许对你有帮助
Java代码
package ThreadTest;
public class ThreadTest3 {
public static void main(String args[]){
MyThread mt = new MyThread() ; // 定义线程对象
Thread t1 = new Thread(mt) ; // 定义Thread对象
// Thread t2 = new Thread(mt) ; // 定义Thread对象
// Thread t3 = new Thread(mt) ; // 定义Thread对象
t1.start() ;
// t2.start() ;
// t3.start() ;
}
}
class MyThread implements Runnable{
private int ticket = 5 ; // 假设一共有5张票
private long start = 0;
public void run(){
sale();
}
private synchronized void sale(){
if (start == 0){
start = System.currentTimeMillis();
}
while(ticket>0){
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("卖票:ticket = " + ticket-- );
}
if (ticket == 0){
System.out.println("cost" + (System.currentTimeMillis() - start));
}
}
}
cost1515
在线程同步下,使用多线程和单线程时间都在1515ms之间,多线程效率并不比单线程效率高
在线程不同步下,使用多线程时间都在906ms之间,多线程效率比单线程效率高
Java代码
package ThreadTest;
public class ThreadTest3 {
public static void main(String args[]){
MyThread mt = new MyThread() ; // 定义线程对象
Thread t1 = new Thread(mt) ; // 定义Thread对象
Thread t2 = new Thread(mt) ; // 定义Thread对象
Thread t3 = new Thread(mt) ; // 定义Thread对象
t1.start() ;
t2.start() ;
t3.start() ;
}
}
class MyThread implements Runnable{
private int ticket = 5 ; // 假设一共有5张票
private long start = 0;
public void run(){
sale();
}
// private synchronized void sale(){
private void sale(){
if (start == 0){
start = System.currentTimeMillis();
System.out.println("cost");
}
while(ticket>0){
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("卖票:ticket = " + ticket-- );
}
if (ticket <= 0){
System.out.println("cost" + (System.currentTimeMillis() - start));
}
}
}
希望对楼主有所帮助。 |