码迷,mamicode.com
首页 > 编程语言 > 详细

Java之线程处理之二

时间:2016-08-14 11:39:33      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

No.1编写一个打印机类

写两个方法

 1 public class Printer {
 2 
 3     public void print1()
 4     {
 5         
 6             System.out.print("微");
 7             System.out.print("冷");
 8             System.out.print("的");
 9             System.out.print("雨");
10             System.out.println();
11     }
12     public void print2()
13     {
14         
15             System.out.print("好");
16             System.out.print("人");
17             System.out.println();
18         
19         
20     }
21 }

目的:为了使两个线程执行该类中的两个方法

线程一:

public class MyThread extends Thread {
    public static Printer p1;
@Override
public void run() {
    for (int i = 1; i <=500; i++) {
        p1.print1();
    }
}

线程二:

public class MyThread2 implements Runnable{
    public static Printer p2;
    @Override
    public void run() {
       for (int i = 1; i <=500; i++) {
            p2.print2();
        }
    }

}

Test类中的方法调用

public class Test {
public static void main(String[] args) {
    Printer p=new Printer();
    MyThread t1=new MyThread();
    t1.p1=p;
    t1.start();
    MyThread2 t2=new MyThread2();
    t2.p2=p;
    Thread t3=new Thread(t2);
    t3.start();
    
}
}

则会出现以下情况:因为程序员不能手动干预cpu分配线程资源

技术分享

解决方法:加上同步锁,使当一个线程执行完之后另一个线程才有执行的权利 

public class Printer {

    public void print1()
    {
        synchronized (this) {
            System.out.print("微");
            System.out.print("冷");
            System.out.print("的");
            System.out.print("雨");
            System.out.println();
        }
        
    }
    public void print2()
    {
        synchronized (this) {
            System.out.print("好");
            System.out.print("人");
            System.out.println();
        }
        
    }
}

解决完毕!!!!!!!!!

Java之线程处理之二

标签:

原文地址:http://www.cnblogs.com/chimingyang/p/5769645.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!