黑马程序员技术交流社区
标题:
如何实现线程同步?
[打印本页]
作者:
hhmm665544
时间:
2014-3-3 13:16
标题:
如何实现线程同步?
class A extends Thread
{
private String name;
Demo1(String name)
{
this.name = name;
}
public void run()
{
for(int x=0;x<60;x++)
{
System.out.println(name+" demo run"+x);
//怎么实现同步
}
}
}
public class Test
{
public static void main(String[] args)
{
Demo1 d1 = new Demo1("one");
Demo1 d2 = new Demo1("two");
d1.start();
d2.start();
}
}
请问下如何实现one线程循环一次后等待two线程执行循环一次,然后再执行one线程?
作者:
itpower
时间:
2014-3-3 13:23
java循环中执行多线程问题-如何在循环中等待一个线程结束后再自动开始新的线程
遇到一个很头疼的难题.执行一个线程,然后该线程里还有一个时间循环的线程(timertask()).我想让时间循环线程每5分钟循环一次,执行两次后就cancel()掉这个timer.然后再重新调用一个新的timer.我现在把该timer线程放入一个while循环中.但执行以后,循环就会同步执行无限个该timer线程,以至内存溢出出错. 有没有什么方法能让这个while循环启动一次timer以后就暂停,直到该timer线程cancel()掉以后,再自动new一个新的timer线程呢?望大侠们指定.我整理的代码如下.那个线程组的代码可以忽略,就理解成开始一个线程就行.
public class Test1{
public static Vector task_counter_t=new Vector();
public static Vector task_counter_r=new Vector();
public static void main(String[] args) {
task_counter_r.insertElementAt(new Main1(),1);
task_counter_t.addElement(new Thread( (Runnable)task_counter_r.elementAt(1)));
((Thread) task_counter_t.elementAt(1)).start();
}
}
class Main1 implements Runnable {
public static boolean go1=true;
public static int tim1=1;
public void run(){
final Timer timera = new Timer()
while(go1){
timera.schedule(new TimerTask() {
public void run() {
tim1++;
if(tim1==4){
tim1=1;
timera.cancel();
}
else {
System.out.printl( "执行一次 ");
}
}, 0,5*1000*60
}
}
复制代码
作者:
hhmm665544
时间:
2014-3-4 14:08
//卖票系统,每个线程卖一张
package com.hmm;
class res1
{
public int num = 100;
public boolean flag = true;
}
class sale1 implements Runnable
{
private res1 r;
sale1(res1 r)
{
this.r = r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(r.flag)
System.out.println("sale1 "+ r.num--);
r.flag = false;
if(r.num<=0)
return;
}
}
}
}
class sale2 implements Runnable
{
private res1 r;
sale2(res1 r)
{
this.r = r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(r.flag == false)
{
System.out.println("sale2 "+ r.num--);
r.flag = true;
if(r.num<=0)
return;
}
}
}
}
}
public class Test2
{
public static void main(String[] args)
{
res1 r = new res1();
Thread d1 = new Thread(new sale1(r));
Thread d2 = new Thread(new sale2(r));
d1.start();
d2.start();
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2