81,092
社区成员
发帖
与我相关
我的任务
分享
/**
* 题:设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。写出程序。
* 以下程序使用内部类实现线程,对j增减的时候没有考虑顺序问题。
*/
public class ThreadTest1{
/** 把J定义为一个对象,以便可以被加锁 */
private Integer j = 0;
public static void main(String args[]){
ThreadTest1 tt=new ThreadTest1();
Inc inc=tt.new Inc();
Dec dec=tt.new Dec();
// 开4个线程跑起来
for(int i=0;i<2;i++){
Thread t=new Thread(inc);
t.start();
t=new Thread(dec);
t.start();
}
}
/** 对J+1 */
private synchronized void inc(){
j++;
try { Thread.sleep((int) Math.random() * 10); } catch (InterruptedException e) { e.printStackTrace(); }
System.out.println(Thread.currentThread().getName()+"-inc:"+j);
}
/** 对J-1 */
private synchronized void dec(){
j--;
System.out.println(Thread.currentThread().getName()+"-dec:"+j);
try { Thread.sleep((int) Math.random() * 10); } catch (InterruptedException e) { e.printStackTrace(); }
}
/** 对J同步加 */
class Inc implements Runnable{
public void run(){
for(int i=0;i<10000;i++){
inc();
}
}
}
/** 对J同步减 */
class Dec implements Runnable{
public void run(){
for(int i=0;i<10000;i++){
dec();
}
}
}
// 运行结果最后一行:Thread-0-inc:0
}
/**
* 题:设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。写出程序。
* 以下程序使用内部类实现线程,对j增减的时候没有考虑顺序问题。
*/
public class ThreadTest1{
/** 把J定义为一个对象,以便可以被加锁 */
private Integer j = 0;
public static void main(String args[]){
ThreadTest1 tt=new ThreadTest1();
Inc inc=tt.new Inc();
Dec dec=tt.new Dec();
// 开4个线程跑起来
for(int i=0;i<2;i++){
Thread t=new Thread(inc);
t.start();
t=new Thread(dec);
t.start();
}
}
/** 对J+1 */
private void inc(){
j++;
try { Thread.sleep((int) Math.random() * 10); } catch (InterruptedException e) { e.printStackTrace(); }
System.out.println(Thread.currentThread().getName()+"-inc:"+j);
}
/** 对J-1 */
private void dec(){
j--;
System.out.println(Thread.currentThread().getName()+"-dec:"+j);
try { Thread.sleep((int) Math.random() * 10); } catch (InterruptedException e) { e.printStackTrace(); }
}
/** 对J同步加 */
class Inc implements Runnable{
public void run(){
for(int i=0;i<10000;i++){
synchronized(j) {
inc();
}
}
}
}
/** 对J同步减 */
class Dec implements Runnable{
public void run(){
for(int i=0;i<10000;i++){
synchronized(j) {
dec();
}
}
}
}
// 运行结果最后一行:Thread-0-inc:25
}